<?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 Feseur\Library\FsrOptionTextVal;
  use Joomla\CMS\Factory;
  use Joomla\CMS\WebAsset\WebAssetManager;
  use Joomla\Component\Formea\Site\Libraries\FormeaEltype;

  class FormeaSelectableCard 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 $is_preview = false;

    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/SelectableCard/joomla.asset.json');
    }

    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)
    {
      $layout = $this->params->get('layout','inline');
      $show_checkmark = (int)$this->params->get('show_checkmark',0);
      $checkmark_position = $this->params->get('checkmark_position','left');
      $is_multiple = (int)$this->params->get('is_multiple',1);
      $gapSize = (int)$this->params->get('gap_size',-1);


      $rowClass = ['formea-sc-row',$layout];
      $rowClass[] = 'row';
      if($gapSize > -1){
        $rowClass[] = 'g-'.$gapSize;
      }


      $input            = '<div class="'.implode(' ',$rowClass).'">';
      $optionLists      = $this->element_values[$langTagUnderscore]['option_lists'];
      $totalOptionLists = count($optionLists);
      $id               = $this->formatElementId();
      for ($i = 0; $i < $totalOptionLists; $i++)
      {
        $inputId  = $id . '_' . $i;
        $selected = false;

        if (!empty($defaultValue))
        {
          if (in_array($optionLists[$i]->val, $defaultValue))
          {
            $selected = true;
          }
        }
        else
        {
          if ($optionLists[$i]->selected)
          {
            $selected = true;
          }
        }
        if($is_multiple > 0){
        $element = $this->drawCheckboxElement($inputId, $optionLists[$i], $selected, $preview);
        }else{
          $element = $this->drawRadioElement($inputId, $optionLists[$i], $selected, $preview);
        }


        $checkmark = '';
        if($show_checkmark > 0){
          $checkmarkClass = 'checkmark-left';
          if($checkmark_position == 'right'){
            $checkmarkClass = 'checkmark-right';
          }
          $checkmark .='<div class="sc-checkmark '.$checkmarkClass.'"><span></span></div>';
        }

        $columnClass = ['sc-block'];
        if($layout === 'inline'){
          $columnSpan = $this->params->get('column_span','3');
          $columnClass[] = 'col-md-'.$columnSpan;
        }else{
          $columnClass[] = 'col-12';
        }

        $input .= '<div class="'.implode(' ',$columnClass).'">';
        if(!$preview){
          $input .= $element;
        }

        $labelClass = ['card'];
        if($preview){
          if($selected){
            $labelClass[] = 'border-primary border-1';
          }
        }
        $input .= '<label for="' . $inputId . '" class="'.implode(' ',$labelClass).'">';
        $input .= '<div class="card-body">';
        $input .= '<div class="sc-content">';
        if($checkmark_position == 'left' && !empty($checkmark)){
          $input .=$checkmark;
        }
        $input .='<div class="sc-rich">';
        $input .= $optionLists[$i]->text;
        $input .= '</div>'; //sc-rich
        if($checkmark_position == 'right' && !empty($checkmark)){
          $input .=$checkmark;
        }
        $input .= '</div>'; //sc-content
        $input .= '</div>'; //.card-body
        $input .= '</label>'; //.card

        $input .= '</div>'; //col-12
      }
      $input .= '</div>';


      return $input;
    }

    protected function drawCheckboxElement($inputId, $optionLists, $selected = false, $preview = false)
    {
      $input = '';
      $input .= '<input type="checkbox" ';
      if (!$preview)
      {
        $input .= 'name="' . $this->formatElementName() . '" ';
      }
      $input .= 'id="' . $inputId . '" ';
      $input .= 'class="sc-element" ';
      $input .= 'value="' . $optionLists->val . '" ';
      if ($selected)
      {
        $input .= 'checked';
      }
      $input .= '/>';

      return $input;
    }
    protected function drawRadioElement($inputId, $optionLists, $selected = false, $preview = false)
    {
      $input = '';
      $input .= '<input type="radio" ';
      if (!$preview)
      {
        $input .= 'name="' . $this->formatElementName() . '" ';
      }
      $input .= 'id="' . $inputId . '" ';
      $input .= 'class="sc-element" ';
      $input .= 'value="' . $optionLists->val . '" ';
      if ($selected)
      {
        $input .= 'checked';
      }
      $input .= '/>';

      return $input;
    }

    public function getInputGroup($class = [], $inputAttributes = [], $langTagUnderscore = '', $preview = false, $labelSetting = null)
    {
      return '';
    }


    public function getOptionLists($langTagUnderscore = '', $defaultValue = '', $submittedData = null, $error_msg = [], $hasError = false)
    {
      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($defaultValue))
      {
        if (is_string($defaultValue))
        {
          $defaultValue = explode(', ', $defaultValue);
        }
      }
      else
      {
        $defaultValue = [];
      }

      if (!empty($this->element_values))
      {
        if (isset($this->element_values[$langTagUnderscore]))
        {
          if (isset($this->element_values[$langTagUnderscore]['option_lists']))
          {
            $radioInputClass = [];
            $themeRadioClass = $themeClass->getInputClass('checkbox');
            if (!empty($themeRadioClass))
            {
              $radioInputClass[] = $themeRadioClass;
            }
            if (!empty($submittedData))
            {
              if ($submittedData->hasError)
              {
                $radioInputClass[] = $themeClass->getErrorClass();
              }
              else
              {
                if ($submittedData->hasSubmittedData)
                {
                  $radioInputClass[] = $themeClass->getNoErrorClass();
                }
              }

            }
            $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="' . implode(' ', $radioInputClass) . '" type="checkbox" ';
                if (!$this->is_preview)
                {
                  $html .= 'name="' . $this->formatElementName() . '" ';
                }
                $html .= 'id="' . $inputId . '" ';
                $html .= 'value="' . $optionLists[$i]->val . '" ';
                if (!empty($defaultValue))
                {
                  if (in_array($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>';
                /*if ($i == $totalOptionLists - 1)
                {
                  $html .= $this->getErrorMsgFeedback($error_msg, $hasError);
                }*/
                $html .= '</div>';
              }
            }
          }
        }
      }
      $html .= $this->getErrorMsgFeedback($error_msg, $hasError);

      return $html;
    }

    public function beforeValidatingInput($element)
    {
      if (isset($element->submitted_value))
      {
        if (!empty($element->submitted_value))
        {
          $element->submitted_value = implode(', ', $element->submitted_value);
        }
      }

      return $element;
    }

    public function preProcessSubmittedValue($submitted_value)
    {
      if (is_array($submitted_value))
      {
        $submitted_value = implode(', ', $submitted_value);
      }

      return $submitted_value;
    }

    public function formatElementName()
    {
      $name = parent::formatElementName();

      return $name . '[]';
    }

    public function getLoadableScript()
    {
      return [
        'com_formea.element.selectable-card'
      ];
    }

    public function getLoadableStyle()
    {
      return [
        //'com_formea.element.Calendar.pickr'
        'com_formea.element.selectable-card'
      ];
    }

  }
