<?php

/**
 * @package     Joomla.Administrator
 * @subpackage  com_formea
 *
 * @copyright   Copyright (C) 2010-2025 Feseur Sdn Bhd. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @version     1.3.0
 */

namespace Joomla\Component\Formea\Administrator\Controller;

defined('_JEXEC') or die;

use Exception;
use Feseur\Library\FsrFieldQuery;
use Feseur\Library\FsrHelper;
use Feseur\Library\FsrResponse;
use Joomla\CMS\Factory;
use Joomla\Filesystem\File;
use Joomla\CMS\HTML\Helpers\Access;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\FormController;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Uri\Uri;
use Joomla\Component\Formea\Administrator\Helper\FormeaHelper;
use Joomla\Component\Formea\Administrator\Model\ElementModel;
use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
use Joomla\Component\Formea\Site\Libraries\FormeaElement;
use Joomla\Component\Formea\Site\Libraries\FormeaEltypes;
use Joomla\Component\Formea\Site\Libraries\FormeaForm;
use Joomla\Component\Formea\Site\Libraries\FormeaGridItem;
use Joomla\Component\Formea\Site\Libraries\FormeaValidations;
use Joomla\Database\DatabaseDriver;
use Joomla\Filesystem\Path;
use Joomla\Registry\Registry;
use stdClass;


/**
 * Controller for a single element
 *
 * @since  1.0
 */
class ElementController extends FormController
{
  /**
   * Method to get a model object, loading it if required.
   *
   * @param   string  $name    The model name. Optional.
   * @param   string  $prefix  The class prefix. Optional.
   * @param   array   $config  Configuration array for model. Optional.
   *
   * @return  BaseDatabaseModel  The model.
   *
   * @since   1.6
   */
  public function getModel($name = 'Element', $prefix = '', $config = array('ignore_request' => true))
  {
    if (empty($name)) {
      $name = $this->context;
    }
    $eltype_name = $this->input->getString('type', null);

    if (!empty($eltype_name)) {
      $config['eltype_name'] = $eltype_name;
    }

    return parent::getModel($name, $prefix, $config);
  }

  /**
   * The prefix to use with controller messages.
   *
   * @var    string
   * @since  1.0.0
   */
  protected $text_prefix = 'COM_FORMEA';


  /**
   * Method to run batch operations.
   *
   * @param   object  $model  The model.
   *
   * @return  boolean   True if successful, false otherwise and internal error is set.
   *
   * @since   1.0
   */
  public function batch($model = null)
  {
    $this->checkToken();

    $model = $this->getModel('Element', 'Administrator', array());

    // Preset the redirect
    $this->setRedirect(Route::_('index.php?option=com_formea&view=elements' . $this->getRedirectToListAppend(), false));

    return parent::batch($model);
  }

  /**
   * Method to edit an existing record.
   *
   * @param   string  $key     The name of the primary key of the URL variable.
   * @param   string  $urlVar  The name of the URL variable if different from the primary key
   *                           (sometimes required to avoid router collisions).
   *
   * @return  boolean  True if access level check and checkout passes, false otherwise.
   *
   * @since   1.6
   */
  public function edit($key = null, $urlVar = null)
  {
    // Do not cache the response to this, its a redirect, and mod_expires and google chrome browser bugs cache it forever!
    $this->app->allowCache(false);
    //check if eltype is set
    $eltype_name = $this->input->getString('type', null);
    /** @var ElementModel $model */
    $model   = $this->getModel();
    $table   = $model->getTable();
    $cid     = (array) $this->input->post->get('cid', array(), 'int');
    $context = "$this->option.edit.$this->context";

    // Determine the name of the primary key for the data.
    if (empty($key)) {
      $key = $table->getKeyName();
    }

    // To avoid data collisions the urlVar may be different from the primary key.
    if (empty($urlVar)) {
      $urlVar = $key;
    }


    if (empty($eltype_name)) {
      $this->setMessage(Text::_('COM_FORMEA_INVALID_ELTYPE_ITEM'), 'error');

      $this->setRedirect(
        Route::_(
          'index.php?option=' . $this->option . '&view=' . $this->view_list
            . $this->getRedirectToListAppend(),
          false
        )
      );

      return false;
    }

    $elementType = $model->getElementType($eltype_name);
    if (empty($elementType)) {
      $this->setMessage(Text::_('COM_FORMEA_INVALID_ELTYPE_NOT_FOUND'), 'error');

      $this->setRedirect(
        Route::_(
          'index.php?option=' . $this->option . '&view=' . $this->view_list
            . $this->getRedirectToListAppend(),
          false
        )
      );

      return false;
    }

    // Get the previous record id (if any) and the current record id.
    $recordId = (int) (count($cid) ? $cid[0] : $this->input->getInt($urlVar));
    $checkin  = $table->hasField('checked_out');

    // Access check.
    if (!$this->allowEdit(array($key => $recordId), $key)) {
      $this->setMessage(Text::_('JLIB_APPLICATION_ERROR_EDIT_NOT_PERMITTED'), 'error');

      $this->setRedirect(
        Route::_(
          'index.php?option=' . $this->option . '&view=' . $this->view_list
            . $this->getRedirectToListAppend(),
          false
        )
      );

      return false;
    }

    // Attempt to check-out the new record for editing and redirect.
    if ($checkin && !$model->checkout($recordId)) {
      // Check-out failed, display a notice but allow the user to see the record.
      $this->setMessage(Text::sprintf('JLIB_APPLICATION_ERROR_CHECKOUT_FAILED', $model->getError()), 'error');

      $this->setRedirect(
        Route::_(
          'index.php?option=' . $this->option . '&view=' . $this->view_item
            . $this->getRedirectToItemAppend($recordId, $urlVar),
          false
        )
      );

      return false;
    } else {
      // Check-out succeeded, push the new record id into the session.
      $this->holdEditId($context, $recordId);
      $this->app->setUserState($context . '.data', null);

      $this->setRedirect(
        Route::_(
          'index.php?option=' . $this->option . '&view=' . $this->view_item
            . $this->getRedirectToItemAppend($recordId, $urlVar),
          false
        )
      );

      return true;
    }
  }

  /**
   * Gets the URL arguments to append to an item redirect.
   *
   * @param   integer  $recordId  The primary key id for the item.
   * @param   string   $urlVar    The name of the URL variable for the id.
   *
   * @return  string  The arguments to append to the redirect URL.
   *
   * @since   1.6
   */
  protected function getRedirectToItemAppend($recordId = null, $urlVar = 'id')
  {
    $append = '';

    // Setup redirect info.
    if ($tmpl = $this->input->get('tmpl', '', 'string')) {
      $append .= '&tmpl=' . $tmpl;
    }

    if ($layout = $this->input->get('layout', 'edit', 'string')) {
      $append .= '&layout=' . $layout;
    }

    if ($forcedLanguage = $this->input->get('forcedLanguage', '', 'cmd')) {
      $append .= '&forcedLanguage=' . $forcedLanguage;
    }

    if ($recordId) {
      $append .= '&' . $urlVar . '=' . $recordId;
    }

    $eltype_name = $this->input->getString('type', null);
    $append      .= '&type=' . $eltype_name;

    $return = $this->input->get('return', null, 'base64');

    if ($return) {
      $append .= '&return=' . $return;
    }

    return $append;
  }

  public function getValidationLists()
  {
    $this->checkToken('get');
    $element_id         = $this->input->getInt('element_id', 0);
    $response           = new FsrResponse();
    $validations        = new FormeaValidations();
    $lists              = $validations->getLists();
    $selectedValidation = [];
    if (!empty($lists)) {
      //$configs       = $validations->getConfigs($lists);
      $totalLists    = count($lists);
      $elValidations = [];
      if ($element_id > 0) {
        $fe                 = new FormeaElement(['element_id' => $element_id]);
        $elValidationsArray = $fe->getValidations();
        $elValidations      = FormeaGeneralHelper::formatKeyArray($elValidationsArray, 'validation_type');
      }
      for ($i = 0; $i < $totalLists; $i++) {
        //$lists[$i]->configs = $configs[$lists[$i]->name];
        if (isset($elValidations[$lists[$i]->name])) {
          $tgt = $elValidations[$lists[$i]->name];
          $t   = $lists[$i];


          if (isset($t->configs) && !empty($t->configs)) {
            foreach ($t->configs as $j => $config) {
              $selectedConditions = [];
              if ($config->isConditions && isset($tgt['conditions'])) {
                if (isset($config->conditions[0])) {
                  foreach ($tgt['conditions'] as $conditionName => $conditionValue) {
                    if ($conditionName === $config->name) {

                      foreach ($conditionValue as $conditionOptionName => $conditionOptionValue) {
                        $condition = $config->conditions[0];
                        if ($conditionOptionName == $condition->name) {
                          $_operators = $condition->operators;

                          foreach ($conditionOptionValue as $fieldVal) {
                            $copiedOperators = array_map(function ($operator) {
                              return clone $operator;
                            }, $_operators);
                            foreach ($copiedOperators as $k => $operator) {
                              $operator->selected = ($operator->val === $fieldVal->operator);
                            }

                            $selectedConditions[$j][] = [
                              'name'      => $conditionOptionName,
                              'text'      => $condition->text,
                              'value'     => $fieldVal->val,
                              'operators' => $copiedOperators,
                              'operator'  => $fieldVal->operator,
                            ];
                          }
                        }
                      }
                    }
                  }
                }
              } else {
                $name = $config->name;
                if (isset($tgt[$name])) {
                  $val = $tgt[$name];

                  if ($config->translatable) {
                    foreach ($config->language_val as $languageVal) {
                      $lang_code = $languageVal->lang_code;

                      if (isset($val[$lang_code])) {
                        $languageVal->value = $val[$lang_code];
                      }
                    }
                  } else {
                    $config->value = $val;

                    foreach ($config->options as $option) {
                      $option->selected = ($option->val === $val);
                    }
                  }
                }
              }

              $config->selectedConditions = $selectedConditions;
            }
          }
          $selectedValidation[] = $t;
        }
      }
    }
    $langTag          = $this->app->getLanguage()->getTag();
    $layoutTextString = FsrHelper::getCommonLanguage(true, [
      JPATH_ROOT . '/administrator/components/com_formea/language/' . $langTag . '/com_formea.ini'
    ], $langTag);

    $ret = [
      'lists'              => $lists,
      'selectedValidation' => $selectedValidation,
      'langString'         => $layoutTextString,
      'label'              => Text::_('COM_FORMEA_VALIDATION_TYPE')
    ];
    //var_dump($ret);die;
    $response->setSuccess(true);
    $response->setResult($ret);
    echo json_encode($response);
    $this->app->close();
  }

  public function getOptionListsVal()
  {
    $this->checkToken('get');
    $element_id        = $this->input->getInt('element_id', 0);
    $element_type_name = $this->input->getString('type');

    $response = new FsrResponse();
    if (empty($element_type_name)) {
      $response->setSuccess(false);
      $response->setMsg('Empty type', 'danger', true);
    } else {
      $optionLists = [];

      /** @var \Joomla\Component\Formea\Site\Model\ElementModel $model */
      $model             = $this->getModel('Element');
      $element_type      = $model->getElementType($element_type_name);
      $langTag           = $this->app->getLanguage()->getTag();
      $langTagUnderscore = str_replace('-', '_', $langTag);
      $langTitle         = $langTag;
      $languages         = FormeaGeneralHelper::getLanguages();
      $elementValues     = [];
      if ($element_id > 0) {
        $formeaElement = new FormeaElement(['element_id' => $element_id]);
        $elementValues = $formeaElement->getValues();
      }

      $totalLanguages = count($languages);
      for ($i = 0; $i < $totalLanguages; $i++) {
        if ($langTag == $languages[$i]->lang_code) {
          $langTitle = $languages[$i]->title;
          break;
        }
      }
      $isMulti = false;
      if (isset($element_type->config->values->isMulti)) {
        $isMulti = filter_var($element_type->config->values->isMulti, FILTER_VALIDATE_BOOLEAN);
      }
      $items = [];
      if (isset($elementValues[$langTagUnderscore])) {
        if (isset($elementValues[$langTagUnderscore]['option_lists'])) {
          if (!empty($elementValues[$langTagUnderscore]['option_lists'])) {
            $items = $elementValues[$langTagUnderscore]['option_lists'];
          }
        }
      }

      $optionLists[] = [
        'lang_code'  => $langTagUnderscore,
        'lang_title' => $langTitle,
        'items'      => $items,
        'isMulti'    => $isMulti
      ];
      $optionLabel   = [
        'label'          => Text::_('COM_FORMEA_DEFAULT_VALUE'),
        'label_value'    => Text::_('COM_FORMEA_VALUE'),
        'label_text'     => Text::_('COM_FORMEA_TEXT'),
        'label_selected' => Text::_('COM_FORMEA_SELECTED'),
        'label_yes'      => Text::_('JYES'),
        'label_no'       => Text::_('JNO'),
        'label_desc'     => Text::_('COM_FORMEA_DEFAULT_VALUE_DESC'),
      ];
      for ($i = 0; $i < $totalLanguages; $i++) {
        if ($langTag != $languages[$i]->lang_code) {
          $items             = [];
          $langTagUnderscore = str_replace('-', '_', $languages[$i]->lang_code);
          if (isset($elementValues[$langTagUnderscore])) {
            if (isset($elementValues[$langTagUnderscore]['option_lists'])) {
              if (!empty($elementValues[$langTagUnderscore]['option_lists'])) {
                $items = $elementValues[$langTagUnderscore]['option_lists'];
              }
            }
          }
          $optionLists[] = [
            'lang_code'  => $langTagUnderscore,
            'lang_title' => $languages[$i]->title,
            'items'      => $items,
            'isMulti'    => $isMulti
          ];
        }
      }

      $ret = [
        'optionLists' => $optionLists,
        'optionLabel' => $optionLabel
      ];
      $response->setSuccess(true);
      $response->setResult($ret);
    }

    echo json_encode($response);
    $this->app->close();
  }

  public function getElementsV2()
  {
    $form_id        = $this->app->getInput()->getInt('form_id', 0);
    $elementFilters = $this->app->getInput()->get('elementFilters', [], 'ARRAY');
    $onlyElements   = filter_var($this->app->getInput()->getInt('onlyElements', 0), FILTER_VALIDATE_BOOLEAN);

    if (!empty($elementFilters)) {
      if (isset($elementFilters['limit'])) {
        $elementFilters['limit']     = (int) $elementFilters['limit'];
        $elementFilters['offset']    = (int) $elementFilters['offset'];
        $elementFilters['eltype_id'] = (int) $elementFilters['eltype_id'];
      }
    }
    $elementFilters = new Registry($elementFilters);

    $langTag = $this->app->getLanguage()->getTag();

    $response = new FsrResponse();
    /** @var FsrFieldQuery[] $whereClause */
    $groupWhereClause = [
      (object) ['field' => 'a.state', 'operator' => '=', 'value' => '1']
    ];

    /** @var FsrFieldQuery[] $whereClause */
    $whereClause = [
      (object) ['field' => 'a.state', 'operator' => '=', 'value' => '1']
    ];

    if (!empty($elementFilters->get('search'))) {
      $whereClause[]      = (object) ['field' => 'a.title', 'operator' => 'LIKE', 'value' => '%' . $elementFilters->get('search') . '%'];
      $groupWhereClause[] = (object) ['field' => 'a.title', 'operator' => 'LIKE', 'value' => '%' . $elementFilters->get('search') . '%'];
    }
    if ($elementFilters->get('eltype_id', 0) > 0) {
      $whereClause[] = (object) ['field' => 'b.id', 'operator' => '=', 'value' => (string) $elementFilters->get('eltype_id')];
    }
    $commonElements = FormeaHelper::getCommonGridItems(
      true,
      $whereClause,
      $groupWhereClause,
      [
        'limit'  => $elementFilters->get('limit', 15),
        'offset' => $elementFilters->get('offset', 0)
      ],
      ['created_date' => 'DESC']
    );
    $elements       = $commonElements['items'];
    $pagination     = $commonElements['pagination'];
    $elementFilters->set('total', $pagination['total']);
    $elementFilters->set('currentPage', $pagination['page']);

    $rendererLists          = [];
    $formTypeOptions        = [];
    $formSetting            = [];
    $langOptions            = [];
    $layoutTextString       = [];
    $elementTypes           = [];
    $batchColumnSetting     = [];
    $defaultGeneralSettings = [];
    $formPages              = [];
    $borderStyleOptions     = [];
    $styleSheetParams       = [];
    $columnOptions          = [];
    $gutterOptions          = [];
    $multiValSettingParams  = [];
    $stdColumnOption        = [];
    $limitFilterOptions     = [];

    /* Added on 1.1.0 */
    $labelSettings = [];
    $languages     = FormeaGeneralHelper::getLanguages(true);
    $langData      = FormeaGeneralHelper::prepareLangData();
    $totalLangData = count($langData);
    for ($ld = 0; $ld < $totalLangData; $ld++) {
      if (isset($languages[$langData[$ld]])) {
        $labelSettings[] = FormeaGeneralHelper::getBlankLabelSetting($langData[$ld], $languages[$langData[$ld]]->title);
      }
    }

    if (!$onlyElements) {
      $app       = Factory::getApplication();
      $lang      = $app->getLanguage();
      $languages = FormeaGeneralHelper::getLanguages(true);

      $langData           = FormeaGeneralHelper::prepareLangData(true);
      $langTagUnderScore  = '';
      $langTitle          = '';
      $batchLabelSettings = [];
      foreach ($langData as $langTagUnderscore => $lang) {
        if (isset($languages[$langTagUnderscore])) {
          if (empty($langTagUnderScore) && empty($langTitle)) {
            $langTagUnderScore = $langTagUnderscore;
            $langTitle         = $languages[$langTagUnderscore]->title;
          }
          $langOptions[]        = (object) [
            'lang_code'  => $langTagUnderscore,
            'lang_title' => $languages[$langTagUnderscore]->title
          ];
          $batchLabelSettings[] = FormeaGeneralHelper::getBlankLabelSetting($langTagUnderscore, $languages[$langTagUnderscore]->title);
        }
      }

      //text string
      $layoutTextString = FsrHelper::getCommonLanguage(true, [
        JPATH_ROOT . '/administrator/components/com_formea/language/' . $langTag . '/com_formea.ini'
      ], $langTag);


      //element Types
      $formeaEltypes = new FormeaEltypes();
      $elTypes       = $formeaEltypes->get(false, ['limit' => -1]);
      $elementTypes  = [];
      if (!empty($elTypes)) {
        $totalElTypes = count($elTypes);
        for ($i = 0; $i < $totalElTypes; $i++) {

          $elTypeImageDetails = [
            'image'     => '',
            'imageSafe' => '',
            'imageType' => 0
          ];
          if (!empty($elTypes[$i]->imageDetails) && isset($elTypes[$i]->imageDetails['image'])) {
            if ($elTypes[$i]->imageDetails['imageType'] === 1) {
              if (is_file(Path::clean(JPATH_ROOT . '/' . $elTypes[$i]->imageDetails['image']))) {
                $elTypeImageDetails['image'] = file_get_contents(JPATH_ROOT . '/' . $elTypes[$i]->imageDetails['image']);
              }
            } else {
              $elTypeImageDetails['image'] = Uri::base() . $elTypes[$i]->imageDetails['image'];
            }
            $elTypeImageDetails['imageType'] = $elTypes[$i]->imageDetails['imageType'];
          }

          $elementTypes[] = (object) [
            'id'           => $elTypes[$i]->id,
            'value_type'   => $elTypes[$i]->value_type,
            'name'         => $elTypes[$i]->name,
            'description'  => $elTypes[$i]->description,
            'title'        => $elTypes[$i]->title,
            'imageDetails' => $elTypeImageDetails,
          ];
        }
      }


      //DefaultGeneralSettings
      $defaultGeneralSettings = FormeaGeneralHelper::getGeneralElementSettings();
      $styleSheetParams       = FormeaGeneralHelper::getStyleSheetParams();

      $batchColumnSetting = (object) [
        'labelSettings' => $batchLabelSettings,
        'column_class'  => '',
        'settings'      => $defaultGeneralSettings
      ];

      $formType        = 0;
      $rendererId      = 0;
      $rendererStyleId = 0;

      if ($form_id > 0) {
        $formeaForm      = new FormeaForm([
          'id'      => $form_id,
          'preview' => true
        ]);
        $formObject      = $formeaForm->getObject();
        $formType        = $formObject->form_type;
        $rendererId      = (int) $formObject->params->get('renderer_id', 0);
        $rendererStyleId = (int) $formObject->params->get('renderer_style_id', 0);
        $formPages       = $formeaForm->getPages(false);
      }

      //borderStyleOptions
      $borderOptions      = FormeaGeneralHelper::getCssBorderStyles();
      $borderStyleOptions = [];
      $totalBorderOptions = count($borderOptions);
      for ($k = 0; $k < $totalBorderOptions; $k++) {
        $val = $borderOptions[$k];
        $txt = Text::_('COM_FORMEA_' . strtoupper($val));
        if ($val === 'none') {
          $val = '';
        }
        $borderStyleOptions[] = [
          'text' => $txt,
          'val' => $val,
          'selected' => false
        ];
      }

      $columnOptions = FormeaGeneralHelper::getFormLayoutColumnOptions();
      $gutterOptions = FormeaGeneralHelper::getGutterOptions();

      /**
       *
       * @var array $multiValSettingParams
       */
      $multiValSettingParams = FormeaGeneralHelper::getMultipleValueSettingParam();

      $stdColumnOption = [];
      for ($l = 1; $l < 13; $l++) {
        $stdColumnOption[] = [
          'text' => (string) $l,
          'val' => $l
        ];
      }

      $limitFilterOptions = [
        5,
        15,
        30,
        50,
      ];

      $multi_enabled = false;

      $rendererLists      = [];
      $formTypeOptions    = [];
      $rendererExtensions = FormeaGeneralHelper::getCoreExtensions(1, [1]);
      if (!empty($rendererExtensions)) {
        $multi_enabled    = true;
        $foundRenderer    = false;
        $totalExtensions  = count($rendererExtensions);
        $targetRendererId = 0;

        for ($j = 0; $j < $totalExtensions; $j++) {
          if ($rendererId === $rendererExtensions[$j]->id) {
            $foundRenderer = true;
          }
          if ($j == 0 && $rendererId < 1) {
            $targetRendererId = $rendererExtensions[$j]->id;
          }
          $rendererStyleDefault = [['text' => 'Default', 'val' => 0]];
          $rendererStyleLists   = FormeaGeneralHelper::getExtensionStyles($rendererExtensions[$j]->id, 0);
          $totalStyleLists      = count($rendererStyleLists);
          for ($m = 0; $m < $totalStyleLists; $m++) {
            $rendererStyleDefault[] = [
              'text' => $rendererStyleLists[$m]->title,
              'val'  => $rendererStyleLists[$m]->id,
            ];
          }
          $rendererLists[] = [
            'extension_id' => $rendererExtensions[$j]->id,
            'title'        => $rendererExtensions[$j]->title,
            'name'         => $rendererExtensions[$j]->name,
            'styles'       => $rendererStyleDefault
          ];
        }
        $formTypeOptions = [
          ['text' => Text::_('COM_FORMEA_SECTION_TYPE_SINGLE'), 'val' => 0],
          ['text' => Text::_('COM_FORMEA_SECTION_TYPE_MULTIPLE'), 'val' => 1]
        ];
        if (!$foundRenderer) {
          $rendererId      = $targetRendererId;
          $rendererStyleId = 0;
        }
      } else {
        $formType        = 0;
        $rendererId      = 0;
        $rendererStyleId = 0;
        if (count($formPages) > 1) {
          $formPages = FormeaGeneralHelper::mergeFormPages($formPages);
        }
      }



      $formSetting = [
        'formType'          => $formType,
        'multi_enabled'     => $multi_enabled,
        'renderer_id'       => $rendererId,
        'renderer_style_id' => $rendererStyleId
      ];
    }

    /*Added 1.0.9*/
    $formeaConfig                 = \Joomla\CMS\Component\ComponentHelper::getParams('com_formea');
    $default_builder_mode         = $formeaConfig->get('builder_mode', 'block');
    $session                      = $this->app->getSession();
    $default_builder_mode_session = $session->get('formea_builder_mode');
    if (!empty($default_builder_mode_session)) {
      $default_builder_mode = $default_builder_mode_session;
    }
    $builderModeLists = [
      (object) [
        'mode'          => 'element',
        'buttonContent' => '<i class="fa-solid fa-shapes"></i>',
        'description'   => Text::_('COM_FORMEA_MODE_ELEMENT_DESC'),
        'selected'      => $default_builder_mode === 'element',
      ],
      (object) [
        'mode'          => 'block',
        'buttonContent' => '<i class="fa-solid fa-cubes"></i>',
        'description'   => Text::_('COM_FORMEA_MODE_BLOCK_DESC'),
        'selected'      => $default_builder_mode === 'block',
      ],
    ];
    $showGrid         = filter_var((int) $formeaConfig->get('show_builder_grid', 1), FILTER_VALIDATE_BOOLEAN);
    $showGrid_session = $session->get('show_builder_grid', null);
    if (!is_null($showGrid_session)) {
      $showGrid = filter_var((int) $showGrid_session, FILTER_VALIDATE_BOOLEAN);
    }

    $groupedElementIcon = file_get_contents(JPATH_ROOT . '/media/com_formea/img/grouped-elements.svg');

    $ret = [
      'rendererLists'          => $rendererLists,
      'formPages'              => $formPages,
      'formTypeOptions'        => $formTypeOptions,
      'formSetting'            => $formSetting,
      'elements'               => $elements,
      'langOptions'            => $langOptions,
      'layoutTextString'       => $layoutTextString,
      'elementTypes'           => $elementTypes,
      'batchColumnSetting'     => $batchColumnSetting,
      'defaultGeneralSettings' => $defaultGeneralSettings,
      'borderStyleOptions'     => $borderStyleOptions,
      'styleSheetParams'       => $styleSheetParams,
      'columnOptions'          => $columnOptions,
      'multiValSettingParams'  => $multiValSettingParams,
      'stdColumnOption'        => $stdColumnOption,
      'limitFilterOptions'     => $limitFilterOptions,
      'gutterOptions'          => $gutterOptions,
      'elementFilters'         => $elementFilters->toArray(),
      'builderModeLists'       => $builderModeLists,
      'showGrid'               => $showGrid,
      'groupedElementIcon'     => $groupedElementIcon,
      'labelSettings'          => $labelSettings
    ];


    $response->setSuccess(true);
    $response->setResult($ret);

    echo json_encode($response);
    $this->app->close();

    //$this->app->close();
  }

  public function getElementDetails()
  {
    $app               = Factory::getApplication();
    $element_id        = $app->getInput()->getInt('element_id', 0);
    $element_type_name = $app->getInput()->getString('type');
    $response          = new FsrResponse();
    if (empty($element_type_name)) {
      $response->setSuccess(false);
      $response->setMsg('Empty type', 'danger', true);
    } else {
      $config = [];
      if ($element_id > 0) {
        $config['element_id'] = $element_id;
      }
      $langData = FormeaGeneralHelper::prepareLangDataVerbose(true);

      $fmElement = new FormeaElement($config);
      $fmElement->set('type', $element_type_name);
      $element = $fmElement->getElement();

      $element->getDetails();
      $details = $element->details;

      $details_rearranged = [];
      foreach ($details as $lang_code => $detail) {
        if (isset($langData[$lang_code])) {
          $details_rearranged[] = (object) [
            'lang_code'  => $langData[$lang_code]['lang_code'],
            'lang_title' => $langData[$lang_code]['lang_title'],
            'detail'     => $detail
          ];
        }
      }
      $element->set('details', $details_rearranged);
      $element->details = $details_rearranged;
      $element->getValues();
      $values            = $element->elementvalues;
      $values_rearranged = [];
      foreach ($values as $lang_code => $detail) {
        if (isset($langData[$lang_code])) {
          $values_rearranged[] = (object) [
            'lang_code'  => $langData[$lang_code]['lang_code'],
            'lang_title' => $langData[$lang_code]['lang_title'],
            'detail'     => $detail
          ];
        }
      }
      $element->elementvalues = $values_rearranged;

      $element->getValidations();
      $element->getElementTypeConfig();
      $element->getAttributes();

      //validations
      $validations         = new FormeaValidations();
      $validationLists     = $validations->getLists();
      $selectedValidations = FormeaHelper::mapSelectedValidations($validationLists, $element->validations);


      $obj                      = new stdClass();
      $obj->id                  = $element->id;
      $obj->title               = $element->title;
      $obj->alias               = $element->alias;
      $obj->type                = $element->type;
      $obj->state               = $element->state;
      $obj->params              = $element->params;
      $obj->checked_out         = $element->checked_out;
      $obj->checked_out_time    = $element->checked_out_time;
      $obj->created_date        = $element->created_date;
      $obj->modified_date       = $element->modified_date;
      $obj->modified_by         = $element->modified_by;
      $obj->created_by          = $element->created_by;
      $obj->access_level        = $element->access_level;
      $obj->publish_up          = $element->publish_up;
      $obj->publish_down        = $element->publish_down;
      $obj->attributes          = $element->attributes;
      $obj->details             = $details_rearranged;
      $obj->elementvalues       = $values_rearranged;
      $obj->elementTypeConfig   = $element->elementTypeConfig;
      $obj->validations         = $element->validations;
      $obj->selectedValidations = $selectedValidations;

      //Access levels
      $ug = Access::assetgroups();


      $ret = [
        'element'          => $obj,
        'accessLevelLists' => $ug,
        'validationLists'  => $validations->getLists()
      ];
      // var_dump($ret);die;

      $response->setSuccess(true);
      $response->setResult($ret);
    }
    echo json_encode($response);
    $this->app->close();
  }

  public function getLayoutElementV2()
  {
    $response = new FsrResponse();
    try {
      $element_id = $this->app->getInput()->getInt('element_id', 0);
      $form_id    = $this->app->getInput()->getInt('form_id', 0);
      $gridId     = $this->app->getInput()->getInt('gridId', 0);
      $pageId     = $this->app->getInput()->getInt('pageId', 0);
      if ($element_id < 1) {
        throw new Exception('Invalid element');
      }
      $langTag = $this->app->getLanguage()->getTag();


      $formeaElement = new FormeaElement(['element_id' => $element_id]);
      $formeaElement->getElementTypeTitle();
      $formeaElement->getElementTypeId();
      $formeaElement->getElementTypeImage();
      $formeaElement->getLabelSettings();
      $element      = $formeaElement->getElement();
      $imageDetails = [
        'image'     => '',
        'imageSafe' => '',
        'imageType' => 0
      ];

      if (!empty($element->imageDetails) && isset($element->imageDetails['image'])) {
        if ($element->imageDetails['imageType'] === 1) {
          $imageDetails['image'] = $element->imageDetails['image'];
          /*if (is_file(Path::clean(JPATH_ROOT . '/' . $element->imageDetails['image'])))
            {
              $imageDetails['image'] = file_get_contents(JPATH_ROOT . '/' . $element->imageDetails['image']);
            }*/
        } else {
          $imageDetails['image'] = Uri::base() . $element->imageDetails['image'];
        }
        $imageDetails['imageType'] = $element->imageDetails['imageType'];
      }
      $labelSettings = $element->labelSettings;

      $styleSheet = '';
      $settings   = FormeaGeneralHelper::getGeneralElementSettings();


      if ($form_id > 0) {
        $container = Factory::getContainer();
        /** @var DatabaseDriver $db */
        $db    = $container->get('DatabaseDriver');
        $query = $db->getQuery(true);
        $query->select('*');
        $query->from($db->quoteName('#__formea_form_elements'));
        $query->where($db->quoteName('form_id') . ' = ' . $db->quote($form_id));
        $query->where($db->quoteName('element_id') . ' = ' . $db->quote($element_id));
        $db->setQuery($query);
        $formElement = $db->loadObject();
        if (!empty($formElement)) {

          $formLabelSetting = json_decode($formElement->labelSettings);

          $totalLabelSetting = count($labelSettings);
          for ($i = 0; $i < $totalLabelSetting; $i++) {
            if (isset($formLabelSetting[$i]->helper_align)) {
              $labelSettings[$i]->helper_align = $formLabelSetting[$i]->helper_align;
            }
            if (isset($formLabelSetting[$i]->setting)) {
              $labelSettings[$i]->setting = $formLabelSetting[$i]->setting;
            }
          }

          $gridId = $formElement->id;

          $styleSheet = $formElement->styleSheet;
          $settings   = json_decode($formElement->settings);
          $pageId     = $formElement->page_id;
        }
      }

      $fmElement = [
        'id'               => $element->id,
        'eltype_id'        => $element->elementTypeId,
        'type'             => $element->type,
        'title'            => $element->title,
        'elementTypeTitle' => $element->elementTypeTitle,
        // 'alias'            => str_replace('-', '_', $element->alias),
        'alias'            => $element->alias,
        'content'          => $element->title,
        'used'             => false,
        'selected'         => false,
        'w'                => 12,
        'x'                => 0,
        'y'                => 0,
        'h'                => 0,
        'minH'             => 2,
        'labelSettings'    => $labelSettings,
        'column_class'     => '',
        'imageDetails'     => $imageDetails,
        'state'            => $element->state,
        'element_id'       => $element->id
      ];

      $gridElement     = [
        'id'               => $gridId,
        'form_id'          => $form_id,
        'page_id'          => $pageId,
        'element_id'       => $element->id,
        'title'            => $element->title,
        'elementTypeTitle' => $element->elementTypeTitle,
        'type'             => $element->type,
        'labelSettings'    => $labelSettings,
        'settings'         => $settings,
        'styleSheet'       => $styleSheet,
        'state'            => $element->state,
        'alias'            => str_replace('-', '_', $element->alias)
        // 'alias'            => $element->alias
      ];
      $elementGridItem = new FormeaGridItem([
        'id'         => $gridId,
        'item_type'  => 2,
        'active'     => false,
        'content'    => (object) $gridElement,
        'settings'   => $settings,
        'styleSheet' => $styleSheet,
      ], false);
      $ret             = [
        'element'         => $fmElement,
        'elementGridItem' => $elementGridItem
      ];

      $response->setSuccess(true);
      $response->setResult($ret);
    } catch (Exception $e) {
      $response->setMsg($e->getMessage());
    }

    echo json_encode($response);
    $this->app->close();
  }

  /**
   * Check whether element or element type exist
   *
   * @return FsrResponse
   * @since 1.1.1
   */
  public function checkElementExistence()
  {
    $response = new FsrResponse();

    try {
      /**
       * 0 - Element Type | 1 - Element | 2 -Grouped Element
       * @var int $checkType
       *
       */
      $checkType = $this->app->getInput()->getInt('checkType', -1);
      $id        = $this->app->getInput()->getInt('elId', 0);
      if ($checkType < 0 || $id < 1) {
        throw new Exception('Invalid params');
      }
      $container = Factory::getContainer();
      /** @var DatabaseDriver $db */
      $db    = $container->get('DatabaseDriver');
      $query = $db->getQuery(true);
      $query->select('COUNT(*)');
      $found = 0;
      if ($checkType == 0) {
        //check element type
        $query->from($db->quoteName('#__formea_eltypes'));
        $query->where($db->quoteName('id') . ' = ' . $db->quote($id));
      } elseif ($checkType == 1) {
        $elTypeName = $this->app->getInput()->getString('elTypeName');
        //check element
        $query->from($db->quoteName('#__formea_elements'));
        $query->where($db->quoteName('id') . ' = ' . $db->quote($id));
        $query->where($db->quoteName('type') . ' = ' . $db->quote($elTypeName));
      } else {
        //Grouped Element
        $query->from($db->quoteName('#__formea_groups'));
        $query->where($db->quoteName('id') . ' = ' . $db->quote($id));
      }
      $db->setQuery($query);
      $found = (int) $db->loadResult();
      $response->setSuccess(true);
      $response->setResult([
        'isExist' => $found > 0
      ]);
    } catch (Exception $e) {
      $response->setMsg($e->getMessage());
    }

    echo json_encode($response);
    $this->app->close();
  }
}
