<?php
  /**
   * @package     Formea.Plugin
   * @subpackage  element
   *
   * @copyright   Copyright (C) 2010-2023 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 Joomla\CMS\Dispatcher\DispatcherInterface;
  use Joomla\CMS\Editor\Editor;
  use Joomla\CMS\Extension\PluginInterface;
  use Joomla\CMS\Factory;
  use Joomla\CMS\HTML\HTMLHelper;
  use Joomla\CMS\Layout\LayoutHelper;
  use Joomla\CMS\Plugin\PluginHelper;
  use Joomla\CMS\WebAsset\WebAssetManager;
  use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
  use Joomla\Component\Formea\Site\Libraries\FormeaElementAttribute;
  use Joomla\Component\Formea\Site\Libraries\FormeaEltype;
  use Joomla\Registry\Registry;

  class FormeaSwitch extends FormeaEltype
  {
    public function __construct($config = [])
    {
      parent::__construct($config);
      $app = Factory::getApplication();
      /** @var WebAssetManager $wa */
      $wa       = $app->getDocument()->getWebAssetManager();
      $registry = $wa->getRegistry();
      $registry->addRegistryFile('components/com_formea/plugins/element/Switch/joomla.asset.json');
    }

    /**
     * @param             $preview
     * @param             $langTag
     * @param             $columnAttributes
     * @param   Registry  $labelSetting
     *
     * @return string
     *
     * @since version
     */
    public function renderField($preview = false, $langTag = '', $columnAttributes = [], $inputAttributes = [], $labelSetting = null)
    {

      $themeClass = $this->getThemeClass();
      if (empty($langTag))
      {
        $langTag = $this->langTag;
      }
      $langTagUnderscore = str_replace('-', '_', $langTag);
      $columnClass       = ['fm_element_' . $this->form_id . '_' . $this->element_id];

      $columnClass        = array_merge($this->element_css_class, $columnClass);
      $labelText          = '';
      $labelClass         = $themeClass->getLabelElClass();
      $inputWrapper       = '';
      $inputWrapperCloser = '';

      $labelPosition   = 'TOP';
      $helperTextAlign = 'LEFT';
      $showLabel       = true;

      $submittedData = $this->getSubmittedElementData();
      $hasError      = $submittedData->hasError;
      $error_msg     = $submittedData->error_msg;
      // var_dump($labelSetting);die;

      if (!empty($labelSetting))
      {
        $labelPosition     = strtoupper($labelSetting->get($langTagUnderscore . '.setting.position', 'TOP'));
        $labelSettingAlign = strtoupper($labelSetting->get($langTagUnderscore . '.setting.align', 'LEFT'));
        $showLabel         = filter_var($labelSetting->get($langTagUnderscore . '.setting.show_label', 'true'), FILTER_VALIDATE_BOOLEAN);
        if ($showLabel)
        {
          if ($labelPosition !== 'TOP' && $labelPosition !== 'BOTTOM')
          {
            $labelColumn   = (int) $labelSetting->get($langTagUnderscore . '.setting.label_column', 12);
            $columnClass[] = $themeClass->getRowClass();

            $labelClass            = array_merge($themeClass->getLabelInlineElClass(), $labelClass);
            $labelClass[]          = $themeClass->getColumnClass($labelColumn);
            $wrapperSize           = $themeClass->getColumnAutoClass();
            $wrapperCalculatedSize = 12 - $labelColumn;
            if ($wrapperCalculatedSize > 0)
            {
              $wrapperSize = $themeClass->getColumnClass($wrapperCalculatedSize);
            }
            $inputWrapper       = '<div class="' . $wrapperSize . '">';
            $inputWrapperCloser = '</div>';
          }
          $labelClass[] = $themeClass->getTextAlignClass($labelSettingAlign);
        }
      }

      if ($hasError)
      {
        $columnClass[] = 'has-error';
      }


      if ($labelPosition === 'TOP')
      {
        $columnClass[] = $themeClass->getFormGroupClass();
      }

      if (isset($columnAttributes['class']))
      {
        $columnClass[] = $columnAttributes['class'];
      }

      $elementClassContainAlignItemCenter = false;

      if (!empty($this->form_element_settings))
      {
        $elementContainerClass = $this->form_element_settings->get('containerClass');
        if (!empty($elementContainerClass))
        {
          if (preg_match("/align-items-/", $elementContainerClass))
          {
            $elementClassContainAlignItemCenter = true;
          }
          $columnClass[] = $this->form_element_settings->get('containerClass');
        }
      }

      if (!$elementClassContainAlignItemCenter)
      {
        $columnClass[] = 'align-items-center';
      }

      $html       = '<div class="' . implode(' ', $columnClass) . '">';
      $inputClass = [];

      if (!empty($this->element_details))
      {
        if (isset($this->element_details[$langTagUnderscore]))
        {
          $labelText = $this->element_details[$langTagUnderscore]['caption'];
          if (isset($this->element_details[$langTagUnderscore]['placeholder']))
          {
            $inputAttributes['placeholder'] = $this->element_details[$langTagUnderscore]['placeholder'];
          }
          if (isset($this->element_details[$langTagUnderscore]['description']))
          {
            $inputAttributes['description'] = $this->element_details[$langTagUnderscore]['description'];
          }
        }
      }
      if (!empty($this->element_values))
      {
        if (isset($this->element_values[$langTagUnderscore]))
        {
          if (isset($this->element_values[$langTagUnderscore]['defval']))
          {
            $inputAttributes['value'] = $this->element_values[$langTagUnderscore]['defval'];
          }
        }
      }

      if ($submittedData->hasSubmittedData)
      {
        $inputAttributes['value'] = $submittedData->submitted_value;
        if (!empty($submittedData->error_css_class))
        {
          $inputClass[] = $submittedData->error_css_class;
        }
        else
        {
          $inputClass[] = $themeClass->getNoErrorClass();
        }
      }


      if ($labelPosition == 'TOP')
      {
        if (!$preview && $showLabel)
        {
          $html .= $this->getLabel($labelText, $labelClass, $preview);
        }
      }


      $elementAttributeClass = new FormeaElementAttribute(['element_id' => $this->element_id]);

      if (!empty($elementAttributeClass))
      {
        $elementAttributes = $elementAttributeClass->getAttributes();
        if (!empty($elementAttributes->class))
        {
          $inputClass[] = $elementAttributes->class;
        }
        foreach ($elementAttributes as $attr => $val)
        {
          if ($attr !== 'class' && $attr !== 'additional_attr')
          {
            $inputAttributes[str_replace('_', '-', $attr)] = $val;
          }
        }
      }
      if ($labelPosition == 'LEFT')
      {
        if (!$preview && $showLabel)
        {
          $html .= $this->getLabel($labelText, $labelClass, $preview);
        }
      }
      $html .= $inputWrapper;

      $html .= $this->getInput($inputClass, $inputAttributes, $langTagUnderscore, $preview, $labelSetting);
      if ($labelPosition == 'BOTTOM')
      {
        if (!$preview && $showLabel)
        {
          $html .= $this->getLabel($labelText, $labelClass, $preview);
        }
      }
      $html .= $this->getErrorMsgFeedback($error_msg, $hasError);
      if (isset($inputAttributes['description']) && !$preview)
      {
        $html .= $this->getHelperText($inputAttributes['description'], $langTagUnderscore, $inputAttributes, $labelSetting);
      }
      $html .= $inputWrapperCloser;
      if ($labelPosition === 'RIGHT')
      {
        if (!$preview && $showLabel)
        {
          $html .= $this->getLabel($labelText, $labelClass, $preview);
        }
      }
      $html .= '</div>';

      return $html;
    }


    public function getInput($class = [], $inputAttributes = [], $langTagUnderscore = '', $preview = false, $labelSetting = null)
    {
      $html = '';
      if ($preview)
      {
        return '<div class="form-check form-switch"><input class="form-check-input" type="checkbox" role="switch"></div>';
      }
      else
      {
        $switch_size = $this->params->get('switch_size', '');

        $html               .= '<div class="form-check form-switch ' . $switch_size . '">';
        $unwantedAttributes = [
          'description',
          'size',
          'max-size'
        ];
        $class[]            = 'form-check-input';

        $html .= '<input class="' . implode(' ', $class) . '" type="checkbox" role="switch" name="' . $this->formatElementName() . '" id="' . $this->formatElementId() . '"';

        foreach ($inputAttributes as $attr => $value)
        {
          if (!in_array($attr, $unwantedAttributes))
          {
            $html .= ' ' . $attr . '="' . $value . '" ';
          }
        }
        $html .= '>';
        $html .= '</div>';
      }

      return $html;
    }

    public function getGeneratedStyle()
    {
      $style = '';
      if ((int) $this->params->get('custom_color', 0) > 0)
      {
        $elementClass      = '.fm_element_' . $this->form_id . '_' . $this->element_id . ' .form-switch .form-check-input';
        $elementClassError = '.fm_element_' . $this->form_id . '_' . $this->element_id . '.has-error .form-switch .form-check-input';
        $elementClassError .= ',.fm_element_' . $this->form_id . '_' . $this->element_id . ' .form-switch .form-check-input.is-invalid';
        $elementClassError .= ',.fm_element_' . $this->form_id . '_' . $this->element_id . '.has-error .form-switch .form-check-input:checked';

        $style .= $elementClass . '{background-color:' . $this->params->get('unchecked_color_bg', '#f8f9fa') . ';';
        $style .= 'border-color:' . $this->params->get('unchecked_color_border', '#dee2e6') . ';';
        $style .= '}';
        $style .= $elementClass . ':checked{background-color:' . $this->params->get('checked_color_bg', '#198754') . ';';
        $style .= 'border-color:' . $this->params->get('checked_color_border', '#dee2e6') . ';';
        $style .= '}';
        $style .= $elementClassError . '{background-color:' . $this->params->get('error_color_bg', '#dc3545') . ';';
        $style .= 'border-color:' . $this->params->get('error_color_border', '#c71b1b') . ';';
        $style .= '}';
      }

      return $style;
    }

    public function getLoadableStyle()
    {
      return [
        'com_formea.element.Switch.main'
      ];
    }

  }
