<?php
    /**
     * @package     Formea.Plugin
     * @subpackage  element
     *
     * @copyright   Copyright (C) 2010-2024 Feseur Sdn Bhd. All rights reserved.
     * @license     GNU General Public License version 2 or later; see LICENSE.txt
     */
// no direct access
    defined('_JEXEC') or die();

    use Feseur\Library\FsrOptionTextVal;
    use Joomla\Component\Formea\Site\Libraries\FormeaEltype;
    use Joomla\CMS\Factory;

    class FormeaRadioButton extends FormeaEltype
    {
        /**
         * @var string
         * @since 1.0.0
         */
        private $layout = 'stacked';

        /**
         * @var string
         * @since 1.0.0
         */
        private $elementClass = '';

        /**
         * @var bool
         * @since 1.0.0
         */
        private $preview = false;

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

        public function getLabel($label = 'label', $class = [], $preview = false)
        {
            return '<label for="' . $this->formatElementId() . '" class="' . implode(' ', $class) . '">' . $label . '</label>';
        }

        public function getInput($class = [], $inputAttributes = [], $langTagUnderscore = '', $preview = false, $labelSetting = null)
        {
            $themeClass = $this->getThemeClass();
            if (empty($langTagUnderscore))
            {
                $langTagUnderscore = $this->langTagUnderscore;
            }

            $themeClass = $this->getThemeClass();
            if (!empty($this->params))
            {
                $this->layout = $this->params->get('layout', 'stacked');
            }
            $this->elementClass = implode(' ', $class);
            $this->preview      = $preview;

            $submittedData = null;
            if (!empty($this->form_id) && $this->form_id > 0)
            {
                $session       = Factory::getApplication()->getSession();
                $submittedData = $session->get('FORMEA_FORM_SUBMISSION_' . $this->form_id);
            }
            $default_value = '';
            if (isset($inputAttributes['value']))
            {
                $default_value = $inputAttributes['value'];
            }

            $error_msg = [];
            $classAttr = [];
            if (!empty($submittedData) && isset($submittedData->elements))
            {
                if (is_array($submittedData->elements))
                {
                    $totalElements = count($submittedData->elements);
                    for ($i = 0; $i < $totalElements; $i++)
                    {
                        if ($submittedData->elements[$i]->element_id === $this->element_id)
                        {
                            if ($submittedData->elements[$i]->validation_error)
                            {
                                $hasError = false;

                                $totalResults = count($submittedData->elements[$i]->validation_result->result);
                                for ($j = 0; $j < $totalResults; $j++)
                                {
                                    if (!empty($submittedData->elements[$i]->validation_result->result[$j]->result->result->msg))
                                    {
                                        $hasError    = true;
                                        $error_msg[] = $submittedData->elements[$i]->validation_result->result[$j]->result->result->msg;
                                    }

                                }
                                if ($hasError)
                                {
                                    $classAttr[] = $themeClass->getErrorClass();
                                }
                            }
                            else
                            {
                                $classAttr[] = $themeClass->getNoErrorClass();
                            }
                            $default_value = $submittedData->elements[$i]->submitted_value;
                            break;
                        }
                    }
                }
            }

            $input = '<div class="' . $themeClass->getBlockClass() . '">';
            $input .= $this->getOptionLists($langTagUnderscore, $default_value);

            $input .= '</div>';


            return $input;
        }

        public function getOptionLists($langTagUnderscore = '', $defaultValue = '')
        {
            if (empty($langTagUnderscore))
            {
                $langTagUnderscore = $this->langTagUnderscore;
            }

            $themeClass = $this->getThemeClass();

            $html                = '';
            $additionalClass     = [];
            $themeContainerClass = $themeClass->getRadioContainerClass(['layout' => $this->layout]);
            if (!empty($themeContainerClass))
            {
                $additionalClass[] = $themeContainerClass;
            }

            if (!empty($this->elementClass))
            {
                $additionalClass[] = $this->elementClass;
            }
            if (!empty($this->element_values))
            {
                if (isset($this->element_values[$langTagUnderscore]))
                {
                    if (isset($this->element_values[$langTagUnderscore]['option_lists']))
                    {
                        $radioInputClass = $themeClass->getInputClass('radio');
                        $id              = $this->formatElementId();
                        /** @var FsrOptionTextVal[] $optionLists */
                        $optionLists = $this->element_values[$langTagUnderscore]['option_lists'];
                        if (is_countable($optionLists))
                        {
                            $totalOptionLists = count($optionLists);
                            for ($i = 0; $i < $totalOptionLists; $i++)
                            {
                                $inputId = $id . '_' . $i;
                                $html    .= '<div class="' . implode(' ', $additionalClass) . '">';
                                $html    .= '<input class="' . $radioInputClass . '" type="radio" ';
                                if (!$this->preview)
                                {
                                    $html .= 'name="' . $this->formatElementName() . '" ';
                                }
                                $html .= 'id="' . $inputId . '" ';
                                $html .= 'value="' . htmlspecialchars($optionLists[$i]->val, ENT_QUOTES) . '" ';
                                if (!empty($defaultValue))
                                {
                                    if ($optionLists[$i]->val === $defaultValue)
                                    {
                                        $html .= 'checked';
                                    }
                                }
                                else
                                {
                                    if ($optionLists[$i]->selected)
                                    {
                                        $html .= 'checked ';
                                    }
                                }
                                $html .= '/>';
                                $html .= '<label class="' . $themeClass->getRadioLabelClass() . '" for="' . $inputId . '">';
                                $html .= $optionLists[$i]->text;
                                $html .= '</label>';
                                $html .= '</div>';
                            }
                        }
                    }
                }
            }

            return $html;
        }
    }
