<?php
  /**
   * @version     1.0.1
   * @package     Joomla 4
   * @subpackage  Formea / Core / ModalSlide
   * @author      Feseur Sdn Bhd
   * @copyright   Copyright (C) 2010 - 2024 Feseur Sdn Bhd
   * @license     GNU/GPL, see LICENSE.php
   */


  defined('_JEXEC') or die();

  // no direct access

  use Feseur\Library\FsrResponse;
  use Joomla\CMS\Factory;
  use Joomla\CMS\Language\Text;
  use Joomla\CMS\WebAsset\WebAssetManager;
  use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
  use Joomla\Component\Formea\Site\Libraries\FormeaCore;
  use Joomla\Database\DatabaseDriver;
  use Joomla\Registry\Registry;

  class FormeaModalSlide extends FormeaCore
  {
    private $modalSlidePath;

    public function __construct($config = [])
    {
      parent::__construct($config);
      $this->modalSlidePath = JPATH_ROOT . '/components/com_formea/plugins/core/ModalSlide/';
      $app                  = Factory::getApplication();
      /** @var WebAssetManager $wa */
      $wa       = $app->getDocument()->getWebAssetManager();
      $registry = $wa->getRegistry();
      $registry->addRegistryFile('components/com_formea/plugins/core/ModalSlide/joomla.asset.json');

    }

    public function storeItem($args = [])
    {
      $app                     = Factory::getApplication();
      $_params                 = new Registry($args);
      $id                      = (int) $_params->get('id', 0);
      $form_id                 = $_params->get('form_id');
      $name                    = $_params->get('name');
      $published               = (int) $_params->get('published', 0);
      $show_type               = (int) $_params->get('show_type', 0);
      $buttonText              = $_params->get('buttonText');
      $buttonClass             = $_params->get('buttonClass');
      $buttonFloat             = (int) $_params->get('buttonFloat', 0);
      $buttonPosition          = $_params->get('buttonPosition');
      $allowHeader             = (int) $_params->get('allowHeader', 0);
      $closeBackdrop           = (int) $_params->get('closeBackdrop', 0);
      $modalVerticallyCentered = (int) $_params->get('modalVerticallyCentered', 0);
      $modalSizeDesktop        = $_params->get('modalSizeDesktop');
      $modalSizeTablet         = $_params->get('modalSizeTablet');
      $modalSizeMobile         = $_params->get('modalSizeMobile');
      $additionalClass         = $_params->get('additionalClass');
      $backdropColor           = $_params->get('backdropColor');
      $backgroundColor         = $_params->get('backgroundColor');
      $backgroundImage         = $_params->get('backgroundImage');
      $backgroundSize          = $_params->get('backgroundSize');
      $backgroundRepeat        = (int) $_params->get('backgroundRepeat', 0);
      $textColor               = $_params->get('textColor');
      $offCanvasPosition       = $_params->get('offCanvasPosition');
      $offCanvasBodyScrolling  = (int) $_params->get('offCanvasBodyScrolling', 0);
      $offCanvasBackdrop       = (int) $_params->get('offCanvasBackdrop', 1);

      $currentDate = new \Feseur\Library\FsrDate();
      $user        = $app->getIdentity();
      $user_id     = 0;
      if (!$user->guest)
      {
        $user_id = $user->id;
      }
      $container = Factory::getContainer();
      /** @var DatabaseDriver $db */
      $db           = $container->get('DatabaseDriver');
      $lang         = $app->getLanguage();
      $langTag      = $lang->getTag();
      $defaultLang  = 'en-GB';
      $languageFile = $this->modalSlidePath . 'language/' . $langTag . '/ModalSlide.ini';
      if (!is_file(\Joomla\Filesystem\Path::clean($languageFile)))
      {
        $languageFile = $this->modalSlidePath . 'language/' . $defaultLang . '/ModalSlide.ini';
      }
      $lang->load('ModalSlide', $this->modalSlidePath, $langTag);

      $datum          = (object) [
        'buttonText'              => $buttonText,
        'buttonClass'             => $buttonClass,
        'buttonFloat'             => $buttonFloat,
        'buttonPosition'          => $buttonPosition,
        'allowHeader'             => $allowHeader,
        'closeBackdrop'           => $closeBackdrop,
        'modalVerticallyCentered' => $modalVerticallyCentered,
        'modalSizeDesktop'        => $modalSizeDesktop,
        'modalSizeTablet'         => $modalSizeTablet,
        'modalSizeMobile'         => $modalSizeMobile,
        'additionalClass'         => $additionalClass,
        'backdropColor'           => $backdropColor,
        'backgroundColor'         => $backgroundColor,
        'backgroundImage'         => $backgroundImage,
        'backgroundSize'          => $backgroundSize,
        'backgroundRepeat'        => $backgroundRepeat,
        'textColor'               => $textColor,
        'offCanvasPosition'       => $offCanvasPosition,
        'offCanvasBodyScrolling'  => $offCanvasBodyScrolling,
        'offCanvasBackdrop'       => $offCanvasBackdrop,
      ];
      $modalSlideItem = [
        'form_id'   => $form_id,
        'name'      => $name,
        'published' => $published,
        'show_type' => $show_type,
        'datum'     => json_encode($datum)
      ];
      $msg            = '';
      if ($id < 1)
      {
        //new
        $modalSlideItem['created_date'] = $currentDate->toSql();
        $modalSlideItem['created_by']   = $user_id;
        $modalSlideItem                 = (object) $modalSlideItem;
        $db->insertObject('#__formea_modalslide', $modalSlideItem);
        $modalSlideItem->id = $db->insertid();
        $msg                = Text::sprintf('MODALSLIDE_CREATE_S_SUCCESS', $name);
      }
      else
      {
        //update
        $modalSlideItem['id']            = $id;
        $modalSlideItem['modified_date'] = $currentDate->toSql();
        $modalSlideItem['modified_by']   = $user_id;
        $modalSlideItem                  = (object) $modalSlideItem;
        $db->updateObject('#__formea_modalslide', $modalSlideItem, 'id');
        $msg = Text::sprintf('MODALSLIDE_UPDATE_S_SUCCESS', $name);
      }
      $modalSlideItem = $this->convertNumberToBoolean($modalSlideItem);
      $formObject     = $this->_getFormObject($modalSlideItem->form_id);

      $form_name = '';
      if (!empty($formObject))
      {
        $form_name = $formObject->title;
      }
      $modalSlideItem->form_name = $form_name;

      return [
        'item' => $modalSlideItem,
        'msg'  => $msg
      ];

    }

    public function getItems($args = [])
    {
      $container = Factory::getContainer();
      /** @var DatabaseDriver $db */
      $db           = $container->get('DatabaseDriver');
      $tableCreated = false;
      try
      {
        $channelColumn = $db->getTableColumns('#__formea_modalslide');
        if (!$channelColumn)
        {
          $tableCreated = $this->seedDb();
        }
        else
        {
          $tableCreated = true;
        }
      }
      catch (Exception $e)
      {
        $tableCreated = $this->seedDb();
      }
      $db_limit = [
        'limit'  => 50,
        'offset' => 0
      ];
      if (isset($args['page']))
      {
        $_page = (int) $args['page'];
        if ($_page > 0)
        {
          $_page--;
        }
        $db_limit['offset'] = 50 * $_page;
      }
      $search = '';
      if (isset($args['search']))
      {
        $search = $args['search'];
      }
      $status     = -1;
      $whereQuery = [];
      if (isset($args['status']))
      {
        $status = (int) $args['status'];
      }

      $getCountries = $this->getItemLists($whereQuery, $db_limit);
      $pagination   = $getCountries['pagination'];
      $items        = $getCountries['items'];
      $totalItems   = count($items);
      for ($j = 0; $j < $totalItems; $j++)
      {
        /*if (empty($items[$j]->form_name))
        {
          $items[$j]->form_name = '';
        }*/
        $items[$j] = $this->convertNumberToBoolean($items[$j]);
      }

      //get the language file
      $app          = Factory::getApplication();
      $lang         = $app->getLanguage();
      $langTag      = $lang->getTag();
      $defaultLang  = 'en-GB';
      $languageFile = $this->modalSlidePath . 'language/' . $langTag . '/ModalSlide.ini';
      if (!is_file(\Joomla\Filesystem\Path::clean($languageFile)))
      {
        $languageFile = $this->modalSlidePath . 'language/' . $defaultLang . '/ModalSlide.ini';
      }
      $lang->load('ModalSlide', $this->modalSlidePath, $langTag);
      $languageString = parse_ini_file($languageFile);

      //get all forms
      $_forms     = $this->_getAllForms();
      $formLists  = [
        (object) [
          'text' => Text::_('MODALSLIDE_UNSET'),
          'val'  => 0
        ]
      ];
      $totalForms = count($_forms);
      for ($i = 0; $i < $totalForms; $i++)
      {

        $text = $_forms[$i]->title;
        if ((int) $_forms[$i]->state !== 1)
        {
          $text .= ' [' . Text::_('JUNPUBLISHED') . ']';
        }
        $formLists[] = (object) [
          'text' => $text,
          'val'  => $_forms[$i]->id
        ];
      }

      //float button position option
      $btnPosition = [
        (object) ['text' => Text::_('MODALSLIDE_TOP'), 'val' => 0],
        (object) ['text' => Text::_('MODALSLIDE_CENTER'), 'val' => 1],
        (object) ['text' => Text::_('MODALSLIDE_BOTTOM'), 'val' => 2],
      ];
      //For top/bottom
      $btnPositionAlt = [
        (object) ['text' => Text::_('MODALSLIDE_LEFT'), 'val' => 0],
        (object) ['text' => Text::_('MODALSLIDE_CENTER'), 'val' => 1],
        (object) ['text' => Text::_('MODALSLIDE_RIGHT'), 'val' => 2],
      ];

      //sizeOption
      $sizeOption    = [
        (object) ['text' => Text::_('MODALSLIDE_SMALL'), 'val' => 'modal-sm'],
        (object) ['text' => Text::_('MODALSLIDE_DEFAULT'), 'val' => ''],
        (object) ['text' => Text::_('MODALSLIDE_LARGE'), 'val' => 'modal-lg'],
        (object) ['text' => Text::_('MODALSLIDE_XLARGE'), 'val' => 'modal-xl'],
        (object) ['text' => Text::_('MODALSLIDE_FULLSCREEN'), 'val' => 'modal-fullscreen'],
      ];
      $sizeOptionAlt = [
        (object) ['text' => Text::_('MODALSLIDE_DEFAULT'), 'val' => ''],
        (object) ['text' => Text::_('MODALSLIDE_FULLSCREEN'), 'val' => 'modal-fullscreen'],
      ];

      $offcanvasPlacementOption = [
        (object) ['text' => Text::_('MODALSLIDE_OFFCANVAS_POSITION_LEFT'), 'val' => 'offcanvas-start'],
        (object) ['text' => Text::_('MODALSLIDE_OFFCANVAS_POSITION_TOP'), 'val' => 'offcanvas-top'],
        (object) ['text' => Text::_('MODALSLIDE_OFFCANVAS_POSITION_RIGHT'), 'val' => 'offcanvas-end'],
        (object) ['text' => Text::_('MODALSLIDE_OFFCANVAS_POSITION_BOTTOM'), 'val' => 'offcanvas-bottom'],
      ];

      return [
        'tableCreated'             => $tableCreated,
        'items'                    => $items,
        'formLists'                => $formLists,
        'btnPosition'              => $btnPosition,
        'btnPositionAlt'              => $btnPositionAlt,
        'sizeOption'               => $sizeOption,
        'sizeOptionAlt'            => $sizeOptionAlt,
        'offcanvasPlacementOption' => $offcanvasPlacementOption,
        'languageString'           => $languageString,
        'pagination'               => $pagination
      ];
    }

    public function removeItem($args = [])
    {
      $app          = Factory::getApplication();
      $lang         = $app->getLanguage();
      $langTag      = $lang->getTag();
      $defaultLang  = 'en-GB';
      $languageFile = $this->modalSlidePath . 'language/' . $langTag . '/ModalSlide.ini';
      if (!is_file(\Joomla\Filesystem\Path::clean($languageFile)))
      {
        $languageFile = $this->modalSlidePath . 'language/' . $defaultLang . '/ModalSlide.ini';
      }
      $lang->load('ModalSlide', $this->modalSlidePath, $langTag);

      $itemIdx   = $args['itemId'];
      $itemName  = $args['itemName'];
      $container = Factory::getContainer();
      /** @var DatabaseDriver $db */
      $db    = $container->get('DatabaseDriver');
      $query = $db->getQuery(true);
      // delete all custom keys for user 1001.
      $conditions = array(
        $db->quoteName('id') . ' = ' . $db->quote($itemIdx)
      );
      $query->delete($db->quoteName('#__formea_modalslide'));
      $query->where($conditions);
      $db->setQuery($query);
      $result = $db->execute();
      if (!$result)
      {
        $msg     = Text::sprintf('MODALSLIDE_DELETE_S_FAILED', $itemName);
        $type    = 'error';
        $deleted = false;
      }
      else
      {
        $msg     = Text::sprintf('MODALSLIDE_DELETE_S_SUCCESS', $itemName);
        $type    = 'success';
        $deleted = true;
      }

      return [
        'deleted' => $deleted,
        'msg'     => $msg,
        'type'    => $type
      ];

    }

    protected function convertNumberToBoolean($item)
    {
      if (empty($item->form_name))
      {
        $item->form_name = '';
      }
      $datum                          = json_decode($item->datum);
      $item->published                = filter_var((int) $item->published, FILTER_VALIDATE_BOOLEAN);
      $datum->buttonFloat             = filter_var((int) $datum->buttonFloat, FILTER_VALIDATE_BOOLEAN);
      $datum->allowHeader             = filter_var((int) $datum->allowHeader, FILTER_VALIDATE_BOOLEAN);
      $datum->closeBackdrop           = filter_var((int) $datum->closeBackdrop, FILTER_VALIDATE_BOOLEAN);
      $datum->modalVerticallyCentered = filter_var((int) $datum->modalVerticallyCentered, FILTER_VALIDATE_BOOLEAN);
      $datum->backgroundRepeat        = filter_var((int) $datum->backgroundRepeat, FILTER_VALIDATE_BOOLEAN);
      $datum->offCanvasBodyScrolling  = filter_var((int) $datum->offCanvasBodyScrolling, FILTER_VALIDATE_BOOLEAN);
      $datum->offCanvasBackdrop       = filter_var((int) $datum->offCanvasBackdrop, FILTER_VALIDATE_BOOLEAN);

      if (empty($item->form_name))
      {
        $item->form_name = '';
      }
      if (empty($item->modified_date))
      {
        $item->modified_date = '';
      }
      if (empty($item->modified_by))
      {
        $item->modified_by = 0;
      }
      if (empty($datum->additionalClass))
      {
        $datum->additionalClass = '';
      }
      if (empty($datum->modalSizeDesktop))
      {
        $datum->modalSizeDesktop = '';
      }
      if (empty($datum->modalSizeTablet))
      {
        $datum->modalSizeTablet = '';
      }
      if (empty($datum->modalSizeMobile))
      {
        $datum->modalSizeMobile = '';
      }
      if (empty($datum->backgroundSize))
      {
        $datum->backgroundSize = '';
      }
      if (empty($datum->textColor))
      {
        $datum->textColor = '';
      }
      if (empty($datum->backdropColor))
      {
        $datum->backdropColor = '';
      }
      if (empty($datum->backgroundColor))
      {
        $datum->backgroundColor = '';
      }
      if (empty($datum->backgroundImage))
      {
        $datum->backgroundImage = '';
      }
      if (empty($datum->buttonClass))
      {
        $datum->buttonClass = '';
      }
      if (empty($datum->buttonPosition))
      {
        $datum->buttonPosition = 0;
      }else{
        $datum->buttonPosition = (int)$datum->buttonPosition;
      }

      $item->datum = $datum;

      return $item;
    }

    /**
     * @param   \Feseur\Library\FsrFieldQuery[]  $whereQuery
     * @param                                    $db_limit
     * @param                                    $ordering
     *
     * @return array
     *
     * @since version
     */
    protected function getItemLists($whereQuery = [], $db_limit = [], $ordering = ['a.id' => 'DESC'])
    {
      $limit  = 50;
      $offset = 0;
      if (!empty($db_limit))
      {
        if (isset($db_limit['limit']))
        {
          $limit = (int) $db_limit['limit'];
        }
        if (isset($db_limit['offset']))
        {
          $offset = (int) $db_limit['offset'];
        }
      }

      $container = Factory::getContainer();
      /** @var DatabaseDriver $db */
      $db    = $container->get('DatabaseDriver');
      $query = $db->getQuery(true);
      $query->select(['a.*', 'b.title AS form_name']);
      $query->from($db->quoteName('#__formea_modalslide', 'a'))
        ->leftJoin($db->quoteName('#__formea_forms', 'b') . ' ON '
          . $db->quoteName('a.form_id') . ' = ' . $db->quoteName('b.id')
        );

      if (!empty($whereQuery))
      {
        foreach ($whereQuery as $clause)
        {
          $v = $db->quote($clause->value);
          if ($clause->value[0] == '(' && $clause->value[strlen($clause->value) - 1] == ')')
          {
            $v = $clause->value;
          }
          $query->where(
            $db->quoteName($clause->field) . ' ' .
            $clause->operator . ' ' .
            $v
          );
        }
      }

      foreach ($ordering as $column => $direction)
      {
        $query->order($db->quoteName($column) . ' ' . $direction);
      }

      if ($limit > 0)
      {
        $query->setLimit($limit, $offset);
      }
      $db->setQuery($query);
      $items = $db->loadObjectList();


      $query = clone $query;
      $query->clear('limit')->clear('offset')->clear('order');
      $db->setQuery($query);
      $db->execute();
      $total = $db->getNumRows();
      $page  = 1;
      if ($offset > 0)
      {
        $page = ceil(($offset + 1) / $limit);
      }
      $fromResult = $offset + 1;
      $toResult   = 0;
      if ($offset + $limit < $total)
      {
        $toResult = $offset + $limit;
      }
      else
      {
        $toResult = $total;
      }
      $ret = [
        'pagination' => [
          'total'      => $total,
          'limit'      => $limit,
          'offset'     => $offset,
          'page'       => (int) $page,
          'fromResult' => $fromResult,
          'toResult'   => $toResult
        ],
        'items'      => $items,
      ];

      return $ret;
    }

    public function onAdminView()
    {
      $app = Factory::getApplication();
      if ($app->isClient('administrator'))
      {
        $container = Factory::getContainer();
        /** @var DatabaseDriver $db */
        $db           = $container->get('DatabaseDriver');
        $tableCreated = false;
        try
        {
          $channelColumn = $db->getTableColumns('#__formea_modalslide');
          if (!$channelColumn)
          {
            $tableCreated = $this->seedDb();
          }
          else
          {
            $tableCreated = true;
          }
        }
        catch (Exception $e)
        {
          $tableCreated = $this->seedDb();
        }
      }
    }

    /**
     * Before core being deleted
     * @return boolean
     *
     * @since 1.1.0
     */
    public function onDeleteCore()
    {
      $container = Factory::getContainer();
      /** @var DatabaseDriver $db */
      $db      = $container->get('DatabaseDriver');
      $query   = 'DROP TABLE IF EXISTS `#__formea_modalslide`;';
      $queries = $db->splitSql($query);
      if (count($queries))
      {
        foreach ($queries as $query)
        {
          $query = trim($query);
          if ($query != '' && $query[0] != '#')
          {
            $db->setQuery($query);
            $db->execute();
          }
        }
      }

      return true;
    }

    /**
     * Method to create the DB table required to temporarily store Stripe data
     * @return true
     *
     * @since 1.1.0
     */
    protected function seedDb()
    {
      $container = Factory::getContainer();
      /** @var DatabaseDriver $db */
      $db      = $container->get('DatabaseDriver');
      $query   = 'CREATE TABLE IF NOT EXISTS `#__formea_modalslide` (
`id` int NOT NULL AUTO_INCREMENT,
`form_id` int NOT NULL,
`name` VARCHAR(255) NULL DEFAULT NULL,
`published` TINYINT NOT NULL DEFAULT \'1\',
`show_type` tinyint(5) NOT NULL DEFAULT \'0\',
`datum` text DEFAULT NULL,
`created_by` int DEFAULT NULL,
`created_date` datetime DEFAULT NULL,
`modified_date` datetime DEFAULT NULL,
`modified_by` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;';
      $queries = $db->splitSql($query);
      if (count($queries))
      {
        foreach ($queries as $query)
        {
          $query = trim($query);
          if ($query != '' && $query[0] != '#')
          {
            $db->setQuery($query);
            $db->execute();
          }
        }
      }

      return true;
    }

    protected function _getAllForms($key = null)
    {
      $container = Factory::getContainer();
      /** @var DatabaseDriver $db */
      $db    = $container->get('DatabaseDriver');
      $query = $db->getQuery(true);
      $query->select('*');
      $query->from($db->quoteName('#__formea_forms'));
      $query->order('id DESC');
      $db->setQuery($query);

      return $db->loadObjectList($key);
    }

    protected function _getFormObject($form_id)
    {
      $container = Factory::getContainer();
      /** @var =DatabaseDriver $db */
      $db    = $container->get('DatabaseDriver');
      $query = $db->getQuery(true);
      $query->select('*');
      $query->from($db->quoteName('#__formea_forms'));
      $query->where($db->quoteName('id') . ' = ' . $db->quote($form_id));
      $db->setQuery($query);

      return $db->loadObject();
    }

    /**
     * Method to render the button
     *
     * @param   int  $modalSlideItemId
     *
     * @return FsrResponse
     *
     * @since 1.1.1
     */
    public function renderButton($modalSlideItemId)
    {
      $response = new FsrResponse();
      try
      {
        $container = Factory::getContainer();
        /** @var DatabaseDriver $db */
        $db    = $container->get('DatabaseDriver');
        $query = $db->getQuery(true);
        $query->select('*');
        $query->from($db->quoteName('#__formea_cores'));
        $query->where($db->quoteName('name') . ' = ' . $db->quote('ModalSlide'));
        $db->setQuery($query);
        $modalSlideCore = $db->loadObject();
        if (empty($modalSlideCore))
        {
          throw new Exception('Modal/Slide not found or unpublished.');
        }
        $params = new Registry($modalSlideCore->params);


        $query->clear();
        $query->select('*');
        $query->from($db->quoteName('#__formea_modalslide'));
        $query->where($db->quoteName('id') . ' = ' . $db->quote($modalSlideItemId));
        $db->setQuery($query);
        $modalSlideItem = $db->loadObject();
        if (empty($modalSlideItem))
        {
          throw new Exception('Modal/Slide item not found.');
        }
        $formId     = $modalSlideItem->form_id;
        $formObject = FormeaGeneralHelper::renderForm($formId, true);
        if (!$formObject->success)
        {
          throw new Exception('Error loading form');
        }
        $formLayout = $formObject->result['content'];

        $itemDatum   = new Registry($modalSlideItem->datum);
        $buttonClass = [$itemDatum->get('buttonClass', 'btn btn-primary')];
        //data-bs-toggle="modal" data-bs-target="#exampleModal"
        $btnAttr = [];

        $_id           = 'FormeaModalSlide_' . $modalSlideItemId . '_' . $formId;
        $buttonClass[] = $_id . '_btn';
        $btnAttr[]     = 'data-bs-target="#' . $_id . '"';
        $btnAttr[]     = 'id="' . $_id . '_btn"';
        $type          = 'modal';
        if ($modalSlideItem->show_type === 0)
        {
          //modal
          $btnAttr[] = 'data-bs-toggle="modal"';
          $panel     = $this->renderModalHtml($itemDatum, $modalSlideItem, $_id, $formLayout);
        }
        else
        {
          //slide panel
          $type      = 'offcanvas';
          $btnAttr[] = 'data-bs-toggle="offcanvas"';
          $panel     = $this->renderOffcanvasHtml($itemDatum, $modalSlideItem, $_id, $formLayout);
        }

        $html = '<button type="button" class="' . implode(' ', $buttonClass) . '" ';
        $html .= implode(' ', $btnAttr);
        $html .= '>';
        $html .= $itemDatum->get('buttonText');
        $html .= '</button>';


        $app = Factory::getApplication();
        /** @var WebAssetManager $wa */
        $wa = $app->getDocument()->getWebAssetManager();

        if ($params->get('load_css'))
        {
          $wa->useStyle('bootstrap.css');
        }
        if ($params->get('load_js'))
        {
          if ($modalSlideItem->show_type === 0)
          {
            $wa->useScript('bootstrap.modal');
          }
          else
          {
            $wa->useScript('bootstrap.offcanvas');
          }
        }
        $floatButton    = (int) $itemDatum->get('buttonFloat') > 0;
        $btnId          = $_id . '_btn';
        $canvasPosition = $itemDatum->get('offCanvasPosition');

        $onShowScript   = '';
        $onHideScript   = '';
        $onHiddenScript = '';

        $script       = 'document.addEventListener("DOMContentLoaded",function(){';


        $onShowScript .= 'var body = document.body;';
        $onShowScript .= 'body.classList.add("' . $_id . '-open");';
        
        $onHiddenScript .= 'var body = document.body;';
        $onHiddenScript .= 'body.classList.remove("' . $_id . '-open");';



        $backdropColor = $itemDatum->get('backdropColor');

        $inlineCss = '';
        if (!empty($backdropColor))
        {
          $inlineCss .= '.' . $_id . '-open .' . $type . '-backdrop';
          $inlineCss .= '{--backdrop-bg:';
          $inlineCss .= $backdropColor . ';';
          if ($modalSlideItem->show_type === 1)
          {
            $inlineCss .= 'background-color:' . $backdropColor;
          }
          $inlineCss .= '} ';
        }

        $backgroundImage = $itemDatum->get('backgroundImage');
        $backgroundColor = $itemDatum->get('backgroundColor');
        $textColor       = $itemDatum->get('textColor');

        if (!empty($backgroundImage) || !empty($backgroundColor) || !empty($textColor))
        {
          if ($modalSlideItem->show_type === 0)
          {
            $inlineCss .= '.' . $_id . '-open .' . $type . ' .modal-content{';
          }
          else
          {
            $inlineCss .= '.' . $_id . '-open .' . $type . '{';
          }
          if (!empty($backgroundImage))
          {
            $inlineCss        .= 'background-image:url("' . $backgroundImage . '");';
            $backgroundRepeat = (int) $itemDatum->get('backgroundRepeat', 0);
            if ($backgroundRepeat > 0)
            {
              $inlineCss .= 'background-repeat:repeat;';
            }
            else
            {
              $inlineCss .= 'background-repeat:no-repeat;';
            }
            $backgroundSize = $itemDatum->get('backgroundSize');
            if (!empty($backgroundSize))
            {
              $inlineCss .= 'background-size:' . $backgroundSize . ';';
            }
          }

          if (!empty($backgroundColor))
          {
            $inlineCss .= 'background-color:' . $backgroundColor . ';';
          }
          if (!empty($textColor))
          {
            $inlineCss .= 'color:' . $textColor . ';';
          }

          $inlineCss .= '} ';
        }


        if ($modalSlideItem->show_type === 1)
        {
          if ($floatButton)
          {
            $wa->useStyle('com_formea.core.ModalSlide.animation');
            //position = 0 -top,1-center,2-bottom
            $btnPosition = (int) $itemDatum->get('buttonPosition', 0);
            $positionCss = '';

            $script .= 'var ' . $btnId . ' = document.getElementById("' . $btnId . '");';
            $script .='var '.$btnId.'_width = '.$btnId.'.offsetWidth;';
            $script .='var '.$btnId.'_height = '.$btnId.'.offsetHeight;';
            $script .='var '.$btnId.'_rect = '.$btnId.'.getBoundingClientRect();';
            $script .='console.log("btnHeight",'.$btnId.'_height);';
            $script .='console.log("btnWidth",'.$btnId.'_width);';
            $script .='console.log("_rect",'.$btnId.'_rect);';
            //$onShowScript .= 'var ' . $btnId . ' = document.getElementById("' . $btnId . '");';
            //$onHideScript .= 'var ' . $btnId . ' = document.getElementById("' . $btnId . '");';
            switch ($canvasPosition)
            {
              case 'offcanvas-start':
                $script .='var '.$btnId.'_offset_x = '.$btnId.'_width - '.$btnId.'_rect.right;';
                $script .= $btnId.'.style.marginLeft = "-" + '.$btnId.'_offset_x  + "px" ;';
                $positionCss = 'left:0;';
                $positionCss .= 'transform: rotate(-90deg);';
                $onShowScript .= $btnId . '.style.animation = "panelStartAnimationOpen .3s ease-in-out forwards";';
                $onHideScript .= $btnId . '.style.animation = "panelStartAnimationClose .3s ease-in-out forwards";';

                if ($btnPosition == 0)
                {
                  $script .= $btnId.'.style.marginTop =   '.$btnId.'_offset_x   + "px" ;';
                  $positionCss .= 'top:0;';
                }
                elseif ($btnPosition == 1)
                {
                  $script .= $btnId.'.style.marginTop =  - '.$btnId.'_offset_x / 2   + "px" ;';
                  $positionCss .= 'top:50%;';
                }
                else
                {
                  $positionCss .= 'bottom:0;';
                  $script .= $btnId.'.style.marginBottom =   '.$btnId.'_offset_x   + "px" ;';
                }
                break;
              case 'offcanvas-end':
                $script .='var '.$btnId.'_offset_x = '.$btnId.'_width - (document.body.clientWidth - '.$btnId.'_rect.left);';
                $script .= $btnId.'.style.marginRight = "-" + '.$btnId.'_offset_x  + "px" ;';
                $positionCss = 'right:0;';
                //$positionCss .= 'transform: translateY(-55%) rotate(-90deg);';
                $positionCss .= 'transform: rotate(-90deg);';
               // $positionCss .= 'transform-origin: bottom right;';
                $onShowScript .= $btnId . '.style.animation = "panelEndAnimationOpen .3s ease-in-out forwards";';
                $onHideScript .= $btnId . '.style.animation = "panelEndAnimationClose .3s ease-in-out forwards";';

                if ($btnPosition == 0)
                {
                  $script .= $btnId.'.style.marginTop =   '.$btnId.'_offset_x   + "px" ;';
                  $positionCss .= 'top:0;';
                }
                elseif ($btnPosition == 1)
                {
                  $script .= $btnId.'.style.marginTop =  - '.$btnId.'_offset_x / 2   + "px" ;';
                  $positionCss .= 'top:50%;';
                }
                else
                {
                  $script .= $btnId.'.style.marginBottom =   '.$btnId.'_offset_x   + "px" ;';
                  $positionCss .= 'bottom:0;';
                }
                break;
              case 'offcanvas-top':
                $positionCss = 'top:0;';
                $positionCss .= 'margin-top:-1px;';
                $onShowScript .= $btnId . '.style.animation = "panelTopAnimationOpen .3s ease-in-out forwards";';
                $onHideScript .= $btnId . '.style.animation = "panelTopAnimationClose .3s ease-in-out forwards";';

                if ($btnPosition == 0)
                {
                  $positionCss .= 'left:0;';
                }
                elseif ($btnPosition == 1)
                {
                  $positionCss .= 'left:40%;';
                }
                else
                {
                  $positionCss .= 'right:0;';
                }
                break;
              default:
                $positionCss = 'bottom:0;';
                $positionCss .= 'margin-bottom:-1px;';
                $onShowScript .= $btnId . '.style.animation = "panelBottomAnimationOpen .3s ease-in-out forwards";';
                $onHideScript .= $btnId . '.style.animation = "panelBottomAnimationClose .3s ease-in-out forwards";';

                if ($btnPosition == 0)
                {
                  $positionCss .= 'left:0;';
                }
                elseif ($btnPosition == 1)
                {
                  $positionCss .= 'left:40%;';
                }
                else
                {
                  $positionCss .= 'right:0;';
                }
                break;
            }
            $inlineCss .= '.' . $_id . '_btn{position:fixed;z-index:1055;';
            $inlineCss .= $positionCss;
            $inlineCss .= '}';
            $inlineCss .= '.' . $_id . '-open .';
          }
        }

        if (!empty($inlineCss))
        {
          $wa->addInlineStyle($inlineCss);
        }



        $script .= 'const ' . $_id . '_El = document.getElementById("' . $_id . '");';
        $script .= $_id . '_El.addEventListener("show.bs.' . $type . '", event => {';
        $script .= $onShowScript;
        $script .= '});';

        if (!empty($onHideScript))
        {
          $script .= $_id . '_El.addEventListener("hide.bs.' . $type . '", event => {';
          $script .= $onHideScript;
          $script .= '});';
        }


        $script .= $_id . '_El.addEventListener("hidden.bs.' . $type . '", event => {';
        $script .= $onHiddenScript;
        $script .= '});';
        $script .= '});';
        $wa->addInlineScript($script);
        $response->setResult([
          'content' => [
            'button' => $html,
            'panel'  => $panel
          ]
        ]);

        $response->setSuccess(true);

      }
      catch (Exception $e)
      {
        $response->setMsg($e->getMessage());
      }

      return $response;
    }


    /**
     * Method to draw HTML bootstrap modal panel
     *
     * @param   Registry  $params
     * @param   stdClass  $modalItem
     * @param   string    $_id
     * @param   string    $formObject
     *
     * @return string
     *
     * @since 1.0.0
     */
    protected function renderModalHtml($params, $modalItem, $_id, $formLayout)
    {
      $modalHeader = '';
      $closeButton = '<button type="button" class="btn-close position-absolute top-0 end-0 mt-2 me-2" data-bs-dismiss="modal" aria-label="Close"></button>';

      $allowHeader         = (int) $params->get('allowHeader', 0);
      $modalDialogClassArr = ['modal-dialog'];
      if ((int) $params->get('modalVerticallyCentered', 0) > 0)
      {
        $modalDialogClassArr[] = 'modal-dialog-centered';
      }
      $modalSizeDesktop = $params->get('modalSizeDesktop');
      if (!empty($modalSizeDesktop))
      {
        $modalDialogClassArr[] = $modalSizeDesktop;
      }
      $modalSizeTablet = $params->get('modalSizeTablet');
      if (!empty($modalSizeTablet))
      {
        $modalDialogClassArr[] = 'modal-fullscreen-md-down';
      }
      $modalSizeMobile = $params->get('modalSizeMobile');
      if (!empty($modalSizeMobile))
      {
        $modalDialogClassArr[] = 'modal-fullscreen-sm-down';
      }

      $modalDialogClass = implode(' ', $modalDialogClassArr);
      $modalClassArr    = ['modal', 'fade'];
      if (!empty($params->get('additionalClass')))
      {
        $modalClassArr[] = $params->get('additionalClass');
      }
      $modalClass   = implode(' ', $modalClassArr);
      $modalAttrArr = ['id="' . $_id . '"', 'tabindex=" - 1"'];
      if ((int) $params->get('closeBackdrop', 0) == 0)
      {
        $modalAttrArr[] = 'data-bs-backdrop="static"';
      }

      $modalAttr = implode(' ', $modalAttrArr);


      if ($allowHeader > 0)
      {
        $modalHeader = <<<HTML
<div class="modal-header">
        <h5 class="modal-title">$modalItem->name</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
HTML;
        $closeButton = '';
      }
      $html = <<<HTML
<div class="$modalClass" $modalAttr>
  <div class="$modalDialogClass">
    <div class="modal-content">
    $modalHeader
      <div class="modal-body">
      $closeButton
        $formLayout
      </div>
    </div>
  </div>
</div>
HTML;

      return $html;
    }

    /**
     * Method to draw HTML bootstrap Offcanvas panel
     *
     * @param   Registry  $params
     * @param   stdClass  $modalItem
     * @param   string    $_id
     * @param   string    $formObject
     *
     * @return string
     *
     * @since 1.0.0
     */
    protected function renderOffcanvasHtml($params, $modalItem, $_id, $formLayout)
    {
      $offcanvasHeader = '';
      $closeButton     = '<button type="button" class="btn-close position-absolute top-0 end-0 mt-2 me-2" data-bs-dismiss="offcanvas" aria-label="Close"></button>';

      $allowHeader = (int) $params->get('allowHeader', 0);

      $offcanvasClassAttr = ['offcanvas', $params->get('offCanvasPosition')];
      if (!empty($params->get('additionalClass')))
      {
        $offcanvasClassAttr[] = $params->get('additionalClass');
      }
      $offcanvasClass = implode(' ', $offcanvasClassAttr);

      $offcanvasAttrArr = ['id="' . $_id . '"', 'tabindex=" - 1"'];

      //data-bs-scroll="true"
      if ((int) $params->get('offCanvasBackdrop', 1) == 0)
      {
        $offcanvasAttrArr[] = 'data-bs-backdrop="false"';
      }
      if ((int) $params->get('offCanvasBodyScrolling', 0) == 1)
      {
        $offcanvasAttrArr[] = 'data-bs-scroll="true"';
      }

      $offcanvasAttr = implode(' ', $offcanvasAttrArr);


      if ($allowHeader > 0)
      {
        $offcanvasHeader = <<<HTML
<div class="offcanvas-header">
    <h5 class="offcanvas-title">$modalItem->name</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
HTML;
        $closeButton     = '';
      }
      $html = <<<HTML
<div class="$offcanvasClass" $offcanvasAttr>
  $offcanvasHeader
  <div class="offcanvas-body">
$closeButton
$formLayout
</div>
</div>
HTML;

      return $html;
    }
  }
