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


    defined('_JEXEC') or die();

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

    class RequiredFieldValidation extends FormeaValidation
    {

        public function validate()
        {
            $retObject       = new FsrResponse();
            $submitted_value = preg_replace('/\s+/', '', $this->submitted_value);
            $submitted_value = (string) $submitted_value;

            $result = (object) [
                'hasError' => false,
                'msg'      => ''
            ];
            if (strlen($submitted_value) === 0)
            {
                $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;
                            }
                        }
                    }
                }
                $result->hasError = true;
                $result->msg      = $msg;
            }
            $retObject->setSuccess(true);
            $retObject->setResult($result);

            return $retObject;
        }

        public function beforeGeneratingLabel($htmlStructure)
        {
            if (!empty($this->params))
            {
                $enabled = (int) $this->params->get('enable_indicator', 0);
                if ($enabled > 0)
                {
                    $indicator       = $this->params->get('indicator', '*');
                    $indicator_color = $this->params->get('indicator_color', '#dc3545');

                    $body                  = $htmlStructure['body'];
                    $body                  .= '<span style="margin-left:5px;color:' . $indicator_color . '">' . $indicator . '</span>';
                    $htmlStructure['body'] = $body;
                }
            }

            return $htmlStructure;
        }

    }
