<?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
   * @version 1.0.4
   */
// no direct access
  defined('_JEXEC') or die();

  use Joomla\CMS\Factory;
  use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
  use Joomla\Component\Formea\Site\Libraries\FormeaElementAttribute;
  use Joomla\Component\Formea\Site\Libraries\FormeaEltype;
  use Joomla\Database\DatabaseDriver;

  class FormeaButton extends FormeaEltype
  {
    public function __construct($config = [])
    {
      parent::__construct($config);
    }

    public function beforeValidatingInput($element)
    {
      $element->skip_value_store = true;

      return $element;
    }

    public function getLabel($label = 'label', $class = 'form-label', $preview = false)
    {
      return '';
    }

    public function getInput($class = [], $inputAttributes = [], $langTagUnderscore = '', $preview = false, $labelSetting = null)
    {
      $themeClass       = $this->getThemeClass();
      $classAttr        = [];
      $themeButtonClass = $themeClass->getInputClass('button');
      if (!is_array($class))
      {
        $class = [$class];
      }

      $buttonType = 'button';
      if (!empty($this->params))
      {
        $buttonType = $this->params->get('input_type', 'button');
      }
      $buttonTypeClass = $themeClass->getButtonTypeElementClass(['input_type' => $buttonType]);

      if (!empty($themeButtonClass))
      {
        $classAttr[] = $themeButtonClass;
      }

      if (!empty($class))
      {
        $classAttr = array_merge($class, $classAttr);
      }
      else
      {
        if (!empty($buttonTypeClass))
        {
          $classAttr[] = $buttonTypeClass;
        }
      }

      $defaultDetail = FormeaGeneralHelper::getDefaultLangValField([
        'caption',
        'placeholder',
        'description'
      ], $this->element_details, 'en-GB');
      $label         = 'button';
      if (isset($defaultDetail['caption']))
      {
        $label = $defaultDetail['caption'];
      }

      $input = '';
      if ($buttonType != 'input')
      {
        $input .= '<button class="' . implode(' ', $classAttr) . '" ';
        if (!$preview)
        {
          if($buttonType == 'submit'){
            $formParams = $this->getFormParams();
            $submission_method = $formParams->get('submission_method','HTTP');
            if($submission_method === 'AJAX'){
              $buttonType = 'button';
              $inputAttributes['onclick'] = 'FormeaFormGeneral.ajaxSubmit('.$this->form_id.',\''.$this->form_id_unique.'\');';
            }
          }
          $input .= 'type="' . $buttonType . '"';

          foreach ($inputAttributes as $key => $value)
          {
            $input .= ' ' . $key . '="' . $value . '" ';
          }
          /*if(isset($inputAttributes['additional_attr'])){
            $input .= ' '.$inputAttributes['additional_attr'].' ';
          }*/
        }
      }
      else
      {
        $input .= '<input class="' . implode(' ', $classAttr) . '" ';
        $formParams = $this->getFormParams();
        $submission_method = $formParams->get('submission_method','HTTP');
        $buttonType = 'submit';
        if($submission_method === 'AJAX'){
          $buttonType = 'button';
          $inputAttributes['onclick'] = 'FormeaAjaxSubmit();';
        }
        $input .= 'type="'.$buttonType.'"';
        if (isset($inputAttributes['placeholder']))
        {
          $input .= 'placeholder="' . $inputAttributes['placeholder'] . '" ';
        }
        if (isset($inputAttributes['value']))
        {
          $input .= 'value="' . $inputAttributes['value'] . '" ';
        }
        if (!$preview)
        {
          $input .= 'name="' . $this->formatElementName() . '"';
          foreach ($inputAttributes as $key => $value)
          {
            $input .= ' ' . $key . '="' . $value . '" ';
          }
        }
      }
      $input .= 'id="' . $this->formatElementId() . '"';
      if ($buttonType != 'input')
      {
        $input .= '>' . $label . '</button>';
      }
      else
      {
        $input .= '/>';
      }

      if (isset($inputAttributes['description']) && !$preview)
      {
        $input .= $this->getHelperText($inputAttributes['description'], $langTagUnderscore, $inputAttributes, $labelSetting);
      }

      return $input;
    }

    public function renderField($preview = false, $langTag = '', $columnAttributes = [], $inputAttributes = [], $labelSetting = null)
    {
      $themeClass = $this->getThemeClass();
      if (empty($langTag))
      {
        $langTag = $this->langTag;
      }
      $langTagUnderscore = str_replace('-', '_', $langTag);

      //$columnClass   = [];
      $columnClass       = ['fm_element_' . $this->form_id . '_' . $this->element_id];
      $formGroupClass= $themeClass->getFormGroupClass();
      if(!empty($formGroupClass)){
        $columnClass[] = $formGroupClass;
      }
      if(isset($inputAttributes['data-formea-conditional-rules'])){
        $columnAttributes['data-formea-conditional-rules'] = $inputAttributes['data-formea-conditional-rules'];
        // unset($inputAttributes['data-formea-conditional-rules']);
      }


      if (isset($columnAttributes['class']))
      {
        $columnClass[] = $columnAttributes['class'];
      }
      //$inputAttributes = null;
      $inputClass      = '';
      if (!empty($this->element_details))
      {
        if (isset($this->element_details[$langTagUnderscore]))
        {
          $label = $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'];
          }
        }
      }


      $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')
          {
            $inputAttributes[$attr] = $val;
          }
        }
      }

      if (!empty($this->form_element_settings))
      {
        if (!empty($this->form_element_settings->get('containerClass')))
        {
          $columnClass[] = $this->form_element_settings->get('containerClass');
        }
      }
      // var_dump($columnClass);die;
      $html = '<div class="' . implode(' ', $columnClass) . '"';
      foreach ($columnAttributes as $attr => $val){
        if($attr != 'class'){
          $html .= ' ' . $attr . '="' . $val . '"';
        }
      }
      $html .='>';
      $html .= $this->getInput($inputClass, $inputAttributes, $langTag, $preview);
      $html .= '</div>';

      return $html;
    }

    public function getLabelSettings($elementDetails = [], $preview = [], $previewBare = [])
    {
      $languages     = FormeaGeneralHelper::getLanguages(true);
      $langData      = FormeaGeneralHelper::prepareLangData();
      $totalLangData = count($langData);
      $ret           = [];
      for ($i = 0; $i < $totalLangData; $i++)
      {
        if (isset($languages[$langData[$i]]))
        {
          $_set = FormeaGeneralHelper::getBlankLabelSetting($langData[$i], $languages[$langData[$i]]->title, $elementDetails, $preview, $previewBare);
          $_set->caption = '';
          $ret[] = $_set;
        }
      }

      return $ret;
    }

    /**
     * Method to get the form params
     * @return \Joomla\Registry\Registry
     *
     * @since 1.1.3
     */
    protected function getFormParams(){
      $json = '{}';
      if($this->form_id > 0){
        $container = Factory::getContainer();
        /** @var DatabaseDriver $db */
        $db = $container->get('DatabaseDriver');
        $query = $db->getQuery(true);
        $query->select('params');
        $query->from($db->quoteName('#__formea_forms'));
        $query->where($db->quoteName('id') . ' = ' . $db->quote($this->form_id));
        $db->setQuery($query);
        $json = $db->loadResult();
        if(empty($json)){
          $json = "{}";
        }
      }
      $formParams = new \Joomla\Registry\Registry($json);
      return $formParams;
    }

  }
