<?php
  /**
   * @version     1.0.0
   * @package     Joomla 5
   * @subpackage  Formea / Core / Backup
   * @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\FormeaAttachment;
  use Joomla\Component\Formea\Site\Libraries\FormeaForm;
  use Joomla\Component\Formea\Site\Libraries\FormeaGroupedElement;
  use Joomla\Component\Formea\Site\Libraries\FormeaImportExportCore;
  use Joomla\Database\DatabaseDriver;
  use Joomla\Filesystem\File;
  use Joomla\Filesystem\Folder;
  use Joomla\Filesystem\Path;
  use Joomla\Registry\Registry;

  class FormeaBackup extends FormeaImportExportCore
  {
    private $backupPath;
    private $generatedMediaPath;

    /**
     * @var DatabaseDriver|null
     * @since 1.0.0
     */
    private $db = null;

    public function __construct($config = [])
    {
      /** @var WebAssetManager $wa */
      parent::__construct($config);
      $this->backupPath         = JPATH_ROOT . '/components/com_formea/plugins/core/Backup/';
      $this->generatedMediaPath = JPATH_ROOT . '/media/com_formea/generated/Backup/';
      /*
       $wa       = $app->getDocument()->getWebAssetManager();
       $registry = $wa->getRegistry();
       $registry->addRegistryFile('components/com_formea/plugins/core/Backup/joomla.asset.json');*/
    }

    private function getDatabase()
    {
      if (empty($this->db))
      {
        $container = Factory::getContainer();
        /** @var DatabaseDriver $db */
        $this->db = $container->get('DatabaseDriver');
      }

      return $this->db;
    }

    public function getData($args = [])
    {
      $langTag = 'en-GB';
      $lang    = $this->app->getLanguage();
      if (isset($args['langTag']))
      {
        $langTag = $args['langTag'];
      }
      else
      {
        $langTag = $lang->getTag();
      }

      $defaultLang  = 'en-GB';
      $languageFile = $this->backupPath . 'language/' . $langTag . '/Backup.ini';
      if (!is_file(\Joomla\Filesystem\Path::clean($languageFile)))
      {
        $languageFile = $this->backupPath . 'language/' . $defaultLang . '/Backup.ini';
      }
      $lang->load('Backup', $this->backupPath, $langTag);
      $languageString = parse_ini_file($languageFile);
      $formLists      = [];
      //get all forms


      $formLists = FormeaGeneralHelper::getFormeaFormLists();

      foreach ($formLists as $form)
      {
        $form->selected = false;
        $form->note     = '';
      }

      $iconLists = [
        'check'      => [
          'svg'     => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="M382-240 154-468l57-57 171 171 367-367 57 57-424 424Z"/></svg>',
          'svgSafe' => ''
        ],
        'empty_tray' => [
          'svg'     => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" ><g><path d="m60.94 42.66-9-25A.992.992 0 0 0 51 17h-9.46c.3-.95.46-1.96.46-3 0-5.51-4.49-10-10-10S22 8.49 22 14c0 1.04.16 2.05.46 3H13c-.42 0-.8.26-.94.66l-9 25c-.04.11-.06.22-.06.34v16c0 .55.45 1 1 1h56c.55 0 1-.45 1-1V43c0-.12-.02-.23-.06-.34zM12 33.83 9.06 42H5.43l6.58-18.27v10.1zM13.7 35h36.59l2.52 7H39.77c-.92 0-1.72.62-1.94 1.52l-.43 1.73c-.11.45-.51.76-.97.76h-8.88c-.46 0-.86-.31-.97-.76l-.43-1.73A2 2 0 0 0 24.21 42H11.17l2.52-7zm41.24 7L52 33.83v-10.1L58.58 42h-3.63zM32 6c4.41 0 8 3.59 8 8 0 3.7-2.51 6.9-6.11 7.78-.29.07-.53.26-.66.52l-1.24 2.47-1.24-2.47a.994.994 0 0 0-.66-.52A7.982 7.982 0 0 1 23.98 14c0-4.41 3.59-8 8-8zm-2.82 17.6 1.93 3.85c.17.34.51.55.89.55s.72-.21.89-.55l1.93-3.85a9.968 9.968 0 0 0 5.84-4.6H50v14H14V19h9.34a9.938 9.938 0 0 0 5.84 4.6zM5 58V44h19.22l.43 1.73A2.986 2.986 0 0 0 27.56 48h8.88c1.38 0 2.58-.93 2.91-2.27l.43-1.73H59v14zm22.76-41.17L30.59 14l-2.83-2.83a.996.996 0 1 1 1.41-1.41L32 12.59l2.83-2.83a.996.996 0 1 1 1.41 1.41L33.41 14l2.83 2.83a.996.996 0 0 1-.71 1.7c-.26 0-.51-.1-.71-.29l-2.83-2.83-2.83 2.83c-.2.2-.45.29-.71.29s-.51-.1-.71-.29a.996.996 0 0 1 0-1.41z"></path></g></svg>',
          'svgSafe' => ''
        ],
      ];

      //get all package lists


      $packageLists = $this->getPackageLists($args);

      $orderingLists = [
        ['text' => 'FORMEA_BACKUP_ORDERING_NEWEST', 'val' => 'id-DESC'],
        ['text' => 'FORMEA_BACKUP_ORDERING_OLDEST', 'val' => 'id-ASC'],
      ];

      return [
        'formLists'      => $formLists,
        'iconSets'       => $iconLists,
        'languageString' => $languageString,
        'packageLists'   => $packageLists,
        'orderingLists'  => $orderingLists,
      ];
    }

    public function generateBackup($args = [])
    {
      $formSelection = [];
      $packageNote   = '';
      $ret           = [
        'proceed' => false,
        'package' => null,
      ];
      if (isset($args['formSelection']))
      {
        $formSelection = $args['formSelection'];
      }
      if (isset($args['packageNote']))
      {
        $packageNote = $args['packageNote'];
      }
      if (!empty($formSelection))
      {
        $user        = $this->app->getIdentity();
        $currentDate = new \Feseur\Library\FsrDate();
        //create package
        $package               = new stdClass();
        $package->created_by   = $user->id;
        $package->modified_by  = 0;
        $package->secret_key   = \Feseur\Library\FsrHelper::generateRandomString(16);
        $package->created_date = $currentDate->toSql();
        $package->filepath     = '';
        $package->note         = $packageNote;
        $container             = Factory::getContainer();
        /** @var DatabaseDriver $db */
        $db = $container->get('DatabaseDriver');
        $db->insertObject('#__formea_backup_packages', $package);
        $package->id       = $db->insertid();
        $package->selected = false;
        $uploadDir         = $this->generatedMediaPath . $package->secret_key . '/';
        //create folder
        if (!is_dir(Path::clean($uploadDir)))
        {
          Folder::create($uploadDir);
          $this->insertBlockerFiles($uploadDir);
        }
        $forms      = [];
        $totalForms = count($formSelection);
        for ($i = 0; $i < $totalForms; $i++)
        {
          $formObject              = new stdClass();
          $formObject->package_id  = $package->id;
          $formObject->form_id     = (int) $formSelection[$i]['form_id'];
          $formObject->form_title  = $formSelection[$i]['form_title'];
          $formObject->title       = $formSelection[$i]['title'];
          $formObject->submissions = ((int) $formSelection[$i]['includeSubmission'] == 0) ? -1 : 0;
          $formObject->elements    = 0;
          $formObject->layouts     = 0;
          $formObject->complete    = 0;
          $formObject->filepath    = '';
          $formObject->note        = (isset($formSelection[$i]['note'])) ? $formSelection[$i]['note'] : '';
          $db->insertObject('#__formea_backup_forms', $formObject);

          $formObject->id       = $db->insertid();
          $formObject->selected = false;
          $forms[]              = $formObject;
          $formDir              = $uploadDir . $formObject->id . '/';
          if (!is_dir(Path::clean($formDir)))
          {
            Folder::create($formDir);
            //$this->insertBlockerFiles($formDir);
          }
        }
        $package->forms = $forms;

        $ret['proceed'] = true;
        $ret['package'] = $package;
      }

      return $ret;
    }

    private function formatBackupArguments($args = [])
    {
      $secret_key = null;
      $package_id = 0;
      $form       = null;
      if (isset($args['secret_key']))
      {
        $secret_key = $args['secret_key'];
      }
      if (isset($args['package_id']))
      {
        $package_id = $args['package_id'];
      }
      if (isset($args['form']))
      {
        if (is_array($args['form']))
        {
          $form = json_decode(json_encode($args['form']));
        }
        else
        {
          $form = $args['form'];
        }

        $form->complete    = (int) $form->complete;
        $form->elements    = (int) $form->elements;
        $form->form_id     = (int) $form->form_id;
        $form->id          = (int) $form->id;
        $form->layouts     = (int) $form->layouts;
        $form->package_id  = (int) $form->package_id;
        $form->submissions = (int) $form->submissions;
      }

      return (object) [
        'secret_key' => $secret_key,
        'package_id' => $package_id,
        'form'       => $form,
      ];
    }


    public function backupElements($args = [])
    {
      $arguments = $this->formatBackupArguments($args);
      if ($arguments->package_id != 0 && !empty($arguments->form))
      {
        $attachments = [];
        $container   = Factory::getContainer();
        /** @var DatabaseDriver $db */
        $db    = $container->get('DatabaseDriver');
        $query = $db->getQuery(true);
        $query->select(['group_id', 'element_id', 'type']);
        $query->from($db->quoteName('#__formea_form_elements'));
        $query->where($db->quoteName('form_id') . ' = ' . $db->quote($arguments->form->form_id));
        $query->where($db->quoteName('target_type') . ' = ' . $db->quote(0));
        $query->order('id ASC');
        $db->setQuery($query);
        $formElements      = $db->loadObjectList();
        $totalFormElements = count($formElements);
        $elementIds        = [];
        $groupIds          = [];
        for ($i = 0; $i < $totalFormElements; $i++)
        {
          if ((int) $formElements[$i]->group_id > 0)
          {
            $groupIds[] = $formElements[$i]->group_id;
          }
          $elementIds[] = $formElements[$i]->element_id;
        }

        $query->clear();
        $query->select('*');
        $query->from($db->quoteName('#__formea_elements'));
        $query->where($db->quoteName('id') . ' IN (' . implode(',', $elementIds) . ')');
        $query->order('id ASC');
        $db->setQuery($query);
        $_elements     = $db->loadObjectList();
        $elements      = [];
        $elementMap    = [];
        $totalElements = count($_elements);
        for ($j = 0; $j < $totalElements; $j++)
        {
          $element_id = $_elements[$j]->id;
          //get the values
          $query->clear();
          $query->select('*');
          $query->from($db->quoteName('#__formea_element_values'));
          $query->where($db->quoteName('element_id') . ' = ' . $db->quote($element_id));
          $query->order('id ASC');
          $db->setQuery($query);
          $values = $db->loadObjectList();
          if (empty($values))
          {
            $values = [];
          }
          else
          {
            $totalValues = count($values);
            for ($k = 0; $k < $totalValues; $k++)
            {
              if (!empty($values[$k]->defval))
              {
                $images = $this->getAllImageSrcFromHtml($values[$k]->defval);
                if (!empty($images))
                {
                  $attachments = array_merge($attachments, $images);
                }
              }
            }
          }
          $_elements[$j]->values = $values;

          //get the validations
          $query->clear();
          $query->select('*');
          $query->from($db->quoteName('#__formea_element_validations'));
          $query->where($db->quoteName('element_id') . ' = ' . $db->quote($element_id));
          $query->order('id ASC');
          $db->setQuery($query);
          $validations = $db->loadObjectList();
          if (empty($validations))
          {
            $validations = [];
          }
          $_elements[$j]->validations = $validations;

          //get the details
          $query->clear();
          $query->select('*');
          $query->from($db->quoteName('#__formea_element_details'));
          $query->where($db->quoteName('element_id') . ' = ' . $db->quote($element_id));
          $query->order('id ASC');
          $db->setQuery($query);
          $details = $db->loadObjectList();
          if (empty($details))
          {
            $details = [];
          }
          $_elements[$j]->details = $details;

          //get the attributes
          $query->clear();
          $query->select('*');
          $query->from($db->quoteName('#__formea_element_attributes'));
          $query->where($db->quoteName('element_id') . ' = ' . $db->quote($element_id));
          $db->setQuery($query);
          $attribute = $db->loadObject();
          if (empty($attribute))
          {
            $attribute = (object) [];
          }
          $_elements[$j]->attribute = $attribute;

          //change the id to a replaceable placeholder

          $name                    = $_elements[$j]->alias;
          $name                    = \Joomla\CMS\Filter\OutputFilter::stringURLSafe($name);
          $name                    = '[' . $arguments->secret_key . '_' . strtoupper(str_replace('-', '_', $name)) . ']';
          $_elements[$j]->id       = $name;
          $elementMap[$element_id] = $name;
          $elements[]              = $_elements[$j];
        }
        $jsonStructure  = [
          'lists' => $elements,
          'map'   => $elementMap
        ];
        $form           = $arguments->form;
        $form->elements = 1;
        $form->complete = $this->checkFormBackupCompletion($form, $arguments);
        $uploadDir      = $this->generatedMediaPath . $arguments->secret_key . '/' . $arguments->form->id . '/';
        $filename       = $uploadDir . 'elements.json';
        File::write($filename, json_encode($jsonStructure));


        if (!empty($attachments))
        {
          $submissionDir = $uploadDir . 'attachments/';
          if (!is_dir(Path::clean($submissionDir)))
          {
            Folder::create($submissionDir);
          }

          $formeaAttachmentClass = new FormeaAttachment();
          $processedFiles        = $formeaAttachmentClass->getRelativeFiles($attachments);
          $totalFiles            = count($processedFiles);
          for ($k = 0; $k < $totalFiles; $k++)
          {
            if (!empty($processedFiles[$k]->cleaned_path) && is_file(Path::clean($processedFiles[$k]->cleaned_path)))
            {
              File::copy($processedFiles[$k]->cleaned_path, $submissionDir . $processedFiles[$k]->name);
            }
          }
        }


        if (!empty($groupIds))
        {
          $this->backupGroupedElements($groupIds, $jsonStructure['map'], $arguments);
        }

        return $form;
      }

      return false;
    }

    public function backupGroupedElements($groupIds, $elementMap, $args = [])
    {
      if (is_array($args))
      {
        $arguments = $this->formatBackupArguments($args);
      }
      else
      {
        $arguments = $args;
      }
      //formea_groups
      if ($arguments->package_id != 0 && !empty($arguments->form))
      {
        $container = Factory::getContainer();
        $db        = $container->get('DatabaseDriver');
        $query     = $db->getQuery(true);
        $query->select('*');
        $query->from($db->quoteName('#__formea_groups'));
        $query->where($db->quoteName('id') . ' IN (' . implode(',', $groupIds) . ')');
        $query->order('id ASC');
        $db->setQuery($query);
        $groups = $db->loadObjectList();

        if (!empty($groups) && !empty($elementMap))
        {
          $totalGroups = count($groups);
          for ($i = 0; $i < $totalGroups; $i++)
          {
            $formeaGroupedElement = new FormeaGroupedElement($groups[$i]->id, [
              'isPreview' => true
            ]);
            $formeaGroupedElement->get();
            $rows               = $formeaGroupedElement->getLayout();
            $grouped_ids        = [];
            $rows               = $this->cleanLayouts($arguments->secret_key, $elementMap, $rows, $grouped_ids);
            $groups[$i]->layout = $rows;

            //get the cores
            $query->clear();
            //formea_group_cores
            $query->select('*');
            $query->from($db->quoteName('#__formea_group_cores'));
            $query->where($db->quoteName('group_id') . ' = ' . $db->quote($groups[$i]->id));
            $query->order('id ASC');
            $db->setQuery($query);
            $cores = $db->loadObjectList();
            if (empty($cores))
            {
              $cores = [];
            }
            $groups[$i]->cores = $cores;
            $groups[$i]->id    = '[' . $arguments->secret_key . '_' . $groups[$i]->id . ']';
          }
          $uploadDir = $this->generatedMediaPath . $arguments->secret_key . '/' . $arguments->form->id . '/';
          $filename  = $uploadDir . 'groupedElements.json';
          File::write($filename, json_encode($groups));
        }
      }

    }

    public function backupSubmissions($args = [])
    {
      $arguments = $this->formatBackupArguments($args);
      if ($arguments->package_id != 0 && !empty($arguments->form))
      {
        $form      = $arguments->form;
        $formId    = $form->form_id;
        $container = Factory::getContainer();
        /** @var DatabaseDriver $db */
        $db    = $container->get('DatabaseDriver');
        $query = $db->getQuery(true);
        $query->select('*');
        $query->from($db->quoteName('#__formea_submissions'));
        $query->where($db->quoteName('form_id') . ' = ' . $db->quote($formId));
        $query->order('id ASC');
        $db->setQuery($query);
        $_submissions     = $db->loadObjectList();
        $submissions      = [];
        $totalSubmissions = count($_submissions);
        $files            = [];
        for ($i = 0; $i < $totalSubmissions; $i++)
        {

          //get submission data
          $query->clear();
          $query->select('*');
          $query->from($db->quoteName('#__formea_submission_data'));
          $query->where($db->quoteName('submission_id') . ' = ' . $db->quote($_submissions[$i]->id));
          $query->order('id ASC');
          $db->setQuery($query);
          $submissionDatas = $db->loadObjectList();
          if (empty($submissionDatas))
          {
            $submissionDatas = [];
          }
          else
          {
            $totalDatas = count($submissionDatas);
            for ($j = 0; $j < $totalDatas; $j++)
            {

              if ($submissionDatas[$j]->group_id > 0)
              {
                $submissionDatas[$j]->group_id = '[' . $arguments->secret_key . '_' . $submissionDatas[$j]->group_id . ']';
              }

              $submissionDatas[$j]->field_id = '[' . $arguments->secret_key . '_' . strtoupper(str_replace('-', '_', $submissionDatas[$j]->field_name)) . ']';

              if ((int) $submissionDatas[$j]->is_link == 1)
              {
                if (!empty($submissionDatas[$j]->dir_path))
                {
                  $dataDirPaths = json_decode($submissionDatas[$j]->dir_path);
                  $files        = array_merge($dataDirPaths, $files);
                }
              }
            }
          }
          $_submissions[$i]->data = $submissionDatas;
          $submissions[]          = $_submissions[$i];
        }

        $form->submissions = 1;
        $form->complete    = $this->checkFormBackupCompletion($form, $arguments);
        $uploadDir         = $this->generatedMediaPath . $arguments->secret_key . '/' . $arguments->form->id . '/';
        $filename          = $uploadDir . 'submissions.json';
        File::write($filename, json_encode($submissions));

        if (!empty($files))
        {
          //$formDir       = $uploadDir . $formId . '/';
          $formDir       = $uploadDir;
          $submissionDir = $formDir . 'submissions/';
          if (!is_dir(Path::clean($submissionDir)))
          {
            Folder::create($submissionDir);
            //$this->insertBlockerFiles($formDir);
          }
          $totalFiles = count($files);
          for ($k = 0; $k < $totalFiles; $k++)
          {
            if (is_file(Path::clean(JPATH_ROOT . '/' . $files[0])))
            {
              $fileInfo = pathinfo(JPATH_ROOT . '/' . $files[0]);
              if (isset($fileInfo['basename']) && !empty($fileInfo['basename']))
              {
                File::copy(JPATH_ROOT . '/' . $files[0], $submissionDir . $fileInfo['basename']);
              }
            }
          }
        }

        return $form;
      }

      return false;
    }

    public function backupLayouts($args = [])
    {
      $arguments = $this->formatBackupArguments($args);
      if ($arguments->package_id != 0 && !empty($arguments->form))
      {
        $form   = $arguments->form;
        $formId = $form->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($formId));
        $db->setQuery($query);
        $_form       = $db->loadObject();
        $pages       = [];
        $attachments = [];
        if (!empty($_form))
        {
          //get all the elements

          $query->clear();
          $query->select(['a.element_id', 'b.alias']);
          $query->from($db->quoteName('#__formea_form_elements', 'a'))->innerJoin(
            $db->quoteName('#__formea_elements', 'b') . ' ON ' . $db->quoteName('a.element_id') . ' = ' . $db->quoteName('b.id')
          );
          $query->where($db->quoteName('a.form_id') . ' = ' . $db->quote($formId));
          $query->where($db->quoteName('a.target_type') . ' = ' . $db->quote(0));
          $db->setQuery($query);
          $elementsByKeyIds = $db->loadAssocList('element_id');

          if (!empty($_form->admin_column))
          {
            $adminColumn = json_decode($_form->admin_column);
          }
          else
          {
            $adminColumn = (object) [];
          }
          $_adminColumn = [];
          foreach ($adminColumn as $element_id => $element_status)
          {
            if (isset($elementsByKeyIds[$element_id]))
            {
              $elementName                = \Joomla\CMS\Filter\OutputFilter::stringURLSafe($elementsByKeyIds[$element_id]['alias']);
              $elementName                = '[' . $arguments->secret_key . '_' . strtoupper(str_replace('-', '_', $elementName)) . ']';
              $_adminColumn[$elementName] = $element_status;
            }
          }
          $_form->admin_column = (object) $_adminColumn;

          //get the emails
          $query->clear();
          $query->select('*');
          $query->from($db->quoteName('#__formea_formemails'));
          $query->where($db->quoteName('form_id') . ' = ' . $db->quote($formId));
          $query->order('id ASC');
          $db->setQuery($query);
          $emails = $db->loadObjectList();
          if (!empty($emails))
          {
            $totalEmails = count($emails);
            for ($k = 0; $k < $totalEmails; $k++)
            {
              //get the email Contents
              $query->clear();
              $query->select('*');
              $query->from($db->quoteName('#__formea_formemailcontent'));
              $query->where($db->quoteName('form_id') . ' = ' . $db->quote($formId));
              $query->where($db->quoteName('email_id') . ' = ' . $db->quote($emails[$k]->id));
              $query->order('id ASC');
              $db->setQuery($query);
              $emailContents      = $db->loadObjectList();
              $totalEmailContents = count($emailContents);
              for ($i = 0; $i < $totalEmailContents; $i++)
              {
                if (!empty($emailContents[$i]->email_content))
                {
                  //check for images
                  $images = $this->getAllImageSrcFromHtml($emailContents[$i]->email_content);
                  if (!empty($images))
                  {
                    $attachments = array_merge($attachments, $images);
                  }
                }
                if (!empty($emailContents[$i]->attachments))
                {
                  $jsonAttachments = json_decode($emailContents[$i]->attachments);
                  $attachments     = array_merge($attachments, $jsonAttachments);
                }
              }
              $emails[$k]->contents = $emailContents;
            }
          }
          else
          {
            $emails = [];
          }
          $_form->emails = $emails;

          //get the details
          $query->clear();
          $query->select('*');
          $query->from($db->quoteName('#__formea_formdetails'));
          $query->where($db->quoteName('form_id') . ' = ' . $db->quote($formId));
          $query->order('id ASC');
          $db->setQuery($query);
          $details = $db->loadObjectList();
          if (empty($details))
          {
            $details = [];
          }
          $_form->details = $details;


          //get the theme
          $query->clear();
          $query->select(['ft.*', 't.name']);
          $query->from($db->quoteName('#__formea_formthemes', 'ft'))->innerJoin(
            $db->quoteName('#__formea_themes', 't') . ' ON ' . $db->quoteName('ft.theme_id') . ' = ' . $db->quoteName('t.id')
          );
          $query->where($db->quoteName('ft.form_id') . ' = ' . $db->quote($formId));
          $db->setQuery($query);
          $theme = $db->loadObject();
          if (!empty($theme))
          {
            $theme->theme_id = '[' . $arguments->secret_key . '_THEME_ID]';
          }
          else
          {
            $theme = (object) [
              'id'       => 0,
              'form_id'  => $formId,
              'theme_id' => 0,
              'style_id' => 0,
              'load_css' => 1,
              'load_js'  => 1,
              'name'     => 'UNKNOWN',
            ];
          }
          $_form->theme = $theme;

          //get the submission settings
          $query->clear();
          $query->select('*');
          $query->from($db->quoteName('#__formea_formsubmissions'));
          $query->where($db->quoteName('form_id') . ' = ' . $db->quote($formId));
          $query->order('id ASC');
          $db->setQuery($query);
          $submissions = $db->loadObjectList();
          if (!empty($submissions))
          {
            $totalSubmissions = count($submissions);
            for ($j = 0; $j < $totalSubmissions; $j++)
            {
              //find images
              $submissionMsgImages   = $this->getAllImageSrcFromHtml($submissions[$j]->submission_msg);
              $submissionErrorImages = $this->getAllImageSrcFromHtml($submissions[$j]->global_error_msg);
              $limitReachMessage     = $this->getAllImageSrcFromHtml($submissions[$j]->limit_reach_msg);
              if (!empty($submissionMsgImages))
              {
                $attachments = array_merge($attachments, $submissionMsgImages);
              }
              if (!empty($submissionErrorImages))
              {
                $attachments = array_merge($attachments, $submissionErrorImages);
              }
              if (!empty($limitReachMessage))
              {
                $attachments = array_merge($attachments, $limitReachMessage);
              }
            }
          }
          else
          {
            $submissions = [];
          }
          $_form->submissions = $submissions;

          //get the cores
          $query->clear();
          $query->select('*');
          $query->from($db->quoteName('#__formea_form_cores'));
          $query->where($db->quoteName('form_id') . ' = ' . $db->quote($formId));
          $query->order('id ASC');
          $db->setQuery($query);
          $cores = $db->loadObjectList();
          if (empty($cores))
          {
            $cores = [];
          }
          $_form->cores = $cores;
        }
        else
        {
          $_form = (object) [];
        }

        //handle grids and layouts
        $formeaForm      = new FormeaForm([
          'id'      => $formId,
          'preview' => true
        ]);
        $elementJsonPath = JPATH_ROOT . '/media/com_formea/generated/Backup/' . $arguments->secret_key . '/' . $arguments->form->id . '/elements.json';
        $grouped_ids     = [];
        if (is_file(Path::clean($elementJsonPath)))
        {
          $elementsJson = json_decode(file_get_contents($elementJsonPath));
          $elementMap   = (array) $elementsJson->map;

          $pages      = $formeaForm->getPages(false);
          $totalPages = count($pages);

          for ($i = 0; $i < $totalPages; $i++)
          {
            $cleanedRows     = $this->cleanLayouts($arguments->secret_key, $elementMap, $pages[$i]->rows, $grouped_ids);
            $pages[$i]->rows = $cleanedRows;
            if (isset($pages[$i]->layout))
            {
              unset($pages[$i]->layout);
            }
            if (isset($pages[$i]->selected))
            {
              unset($pages[$i]->selected);
            }

          }
        }

        $form->layouts  = 1;
        $form->complete = $this->checkFormBackupCompletion($form, $arguments);
        $uploadDir      = $this->generatedMediaPath . $arguments->secret_key . '/' . $arguments->form->id . '/';
        $filename       = $uploadDir . 'layouts.json';
        $formfilename   = $uploadDir . 'form.json';
        File::write($filename, json_encode($pages));
        File::write($formfilename, json_encode($_form));

        if (!empty($grouped_ids))
        {
          $groupedMapFilename = $uploadDir . 'grouped_map.json';
          File::write($groupedMapFilename, json_encode($grouped_ids));
        }

        if (!empty($attachments))
        {
          $attachments = array_values(array_flip(array_flip($attachments)));


          //$formDir       = $uploadDir . $formId . '/';
          $formDir       = $uploadDir;
          $submissionDir = $formDir . 'attachments/';
          if (!is_dir(Path::clean($submissionDir)))
          {
            Folder::create($submissionDir);
            //$this->insertBlockerFiles($formDir);
          }

          $formeaAttachmentClass = new FormeaAttachment();
          $processedFiles        = $formeaAttachmentClass->getRelativeFiles($attachments);
          $totalFiles            = count($processedFiles);
          for ($k = 0; $k < $totalFiles; $k++)
          {
            if (!empty($processedFiles[$k]->cleaned_path) && is_file(Path::clean($processedFiles[$k]->cleaned_path)))
            {
              File::copy($processedFiles[$k]->cleaned_path, $submissionDir . $processedFiles[$k]->name);
            }

          }
        }


        return $form;
      }

      return false;
    }

    public function cleanLayouts($secretKey, $elementJsons, $layouts = [], &$group_ids = [])
    {
      $totalLayouts              = count($layouts);
      $labelSettingRemovableKeys = [
        'preview',
        'previewSafe',
        'previewBare',
        'previewBareSafe',
      ];
      for ($i = 0; $i < $totalLayouts; $i++)
      {

        if (is_int($layouts[$i]->group_id))
        {
          if ($layouts[$i]->group_id > 0)
          {
            $key                               = '[' . $secretKey . '_' . $layouts[$i]->group_id . ']';
            $group_ids[$layouts[$i]->group_id] = $key;
            $layouts[$i]->group_id             = $key;
          }
        }

        if ($layouts[$i]->item_type == 3)
        {
          if (isset($layouts[$i]->inputGroupItem) && !empty($layouts[$i]->inputGroupItem))
          {
            if (isset($layouts[$i]->inputGroupItem['labelSettings']) && !empty($layouts[$i]->inputGroupItem['labelSettings']))
            {
              $totalLabelSettings = count($layouts[$i]->inputGroupItem['labelSettings']);
              for ($j = 0; $j < $totalLabelSettings; $j++)
              {
                foreach ($labelSettingRemovableKeys as $removeableKey)
                {
                  if (isset($layouts[$i]->inputGroupItem['labelSettings'][$j]->{$removeableKey}))
                  {
                    unset($layouts[$i]->inputGroupItem['labelSettings'][$j]->{$removeableKey});
                  }
                }
              }
            }
            if (isset($layouts[$i]->inputGroupItem['elements']) && !empty($layouts[$i]->inputGroupItem['elements']))
            {
              $totalElements = count($layouts[$i]->inputGroupItem['elements']);
              for ($j = 0; $j < $totalElements; $j++)
              {
                if (isset($layouts[$i]->inputGroupItem['elements'][$j]->labelSettings) && !empty($layouts[$i]->inputGroupItem['elements'][$j]->labelSettings))
                {
                  $totalLabelSettings = count($layouts[$i]->inputGroupItem['elements'][$j]->labelSettings);
                  for ($k = 0; $k < $totalLabelSettings; $k++)
                  {
                    foreach ($labelSettingRemovableKeys as $removeableKey)
                    {
                      if (isset($layouts[$i]->inputGroupItem['elements'][$j]->labelSettings[$k]->{$removeableKey}))
                      {
                        unset($layouts[$i]->inputGroupItem['elements'][$j]->labelSettings[$k]->{$removeableKey});
                      }
                    }
                  }

                }

                if (isset($layouts[$i]->inputGroupItem['elements'][$j]->imageDetails))
                {
                  unset($layouts[$i]->inputGroupItem['elements'][$j]->imageDetails);
                }

                if (isset($layouts[$i]->inputGroupItem['elements'][$j]->element_id))
                {
                  if (isset($elementJsons[$layouts[$i]->inputGroupItem['elements'][$j]->element_id]))
                  {
                    $layouts[$i]->inputGroupItem['elements'][$j]->element_id = $elementJsons[$layouts[$i]->inputGroupItem['elements'][$j]->element_id];
                  }
                }

              }
            }

            if (isset($layouts[$i]->inputGroupItem['elementsPreview']))
            {
              unset($layouts[$i]->inputGroupItem['elementsPreview']);
            }

            if (isset($layouts[$i]->inputGroupItem['elementsPreviewSafe']))
            {
              unset($layouts[$i]->inputGroupItem['elementsPreviewSafe']);
            }

            if (isset($layouts[$i]->inputGroupItem['rows']) && !empty($layouts[$i]->inputGroupItem['rows']))
            {
              $rows                                = $this->cleanLayouts($secretKey, $elementJsons, $layouts[$i]->inputGroupItem['rows'], $group_ids);
              $layouts[$i]->inputGroupItem['rows'] = $rows;
            }

          }

        }
        else
        {
          if (isset($layouts[$i]->content) && !empty($layouts[$i]->content))
          {
            if (isset($layouts[$i]->content->labelSettings))
            {
              $totalLabelSettings = count($layouts[$i]->content->labelSettings);
              for ($j = 0; $j < $totalLabelSettings; $j++)
              {
                foreach ($labelSettingRemovableKeys as $removeableKey)
                {
                  if (isset($layouts[$i]->content->labelSettings[$j]->{$removeableKey}))
                  {
                    unset($layouts[$i]->content->labelSettings[$j]->{$removeableKey});
                  }
                }
              }
            }
            if (isset($layouts[$i]->content->imageDetails))
            {
              unset($layouts[$i]->content->imageDetails);
            }
            if (isset($layouts[$i]->content->element_id))
            {
              if (isset($elementJsons[$layouts[$i]->content->element_id]))
              {
                $layouts[$i]->content->element_id = $elementJsons[$layouts[$i]->content->element_id];
              }
            }
          }
        }

        if (!empty($layouts[$i]->sets))
        {
          $totalSets = count($layouts[$i]->sets);
          for ($l = 0; $l < $totalSets; $l++)
          {
            if (isset($layouts[$i]->sets[$l]['labelSettings']) && !empty($layouts[$i]->sets[$l]['labelSettings']))
            {
              $totalLabelSettings = count($layouts[$i]->sets[$l]['labelSettings']);
              for ($j = 0; $j < $totalLabelSettings; $j++)
              {
                foreach ($labelSettingRemovableKeys as $removeableKey)
                {
                  if (isset($layouts[$i]->sets[$l]['labelSettings'][$j]->{$removeableKey}))
                  {
                    unset($layouts[$i]->sets[$l]['labelSettings'][$j]->{$removeableKey});
                  }
                }
              }
            }
            if (isset($layouts[$i]->sets[$l]['elementsPreview']))
            {
              unset($layouts[$i]->sets[$l]['elementsPreview']);
            }
            if (isset($layouts[$i]->sets[$l]['elementsPreviewSafe']))
            {
              unset($layouts[$i]->sets[$l]['elementsPreviewSafe']);
            }
          }
        }

        if (!empty($layouts[$i]->items))
        {
          $items              = $this->cleanLayouts($secretKey, $elementJsons, $layouts[$i]->items, $group_ids);
          $layouts[$i]->items = $items;
        }

      }

      return $layouts;
    }

    public function getPackageLists($args = [])
    {
      $db_limit = [
        'limit'  => 5,
        'offset' => 0,
      ];
      $ordering = ['id' => 'DESC'];
      if (isset($args['limit']))
      {
        $db_limit['limit'] = (int) $args['limit'];
      }
      if (isset($args['offset']))
      {
        $db_limit['offset'] = (int) $args['offset'];
      }
      $search = '';
      if (isset($args['search']))
      {
        $search = $args['search'];
      }
      if (isset($args['ordering']))
      {
        $ordering                = [];
        $_ordering               = explode('-', $args['ordering']);
        $ordering[$_ordering[0]] = $_ordering[1];
      }

      $packageLists = $this->packageLists($db_limit, $ordering, $search);
      if (!empty($packageLists))
      {
        return $packageLists;
      }
      else
      {
        return null;
      }

    }

    public function deletePackages($args = [])
    {
      $packageIds = [];
      $packages   = [];
      if (isset($args['packages']))
      {
        $packages = $args['packages'];
      }

      foreach ($packages as $package)
      {
        $packageIds[] = $package['id'];
      }


      $db    = $this->getDatabase();
      $query = $db->getQuery(true);
      // delete all custom keys for user 1001.
      $conditions = array(
        $db->quoteName('id') . ' IN (' . implode(',', $packageIds) . ')'
      );
      $query->delete($db->quoteName('#__formea_backup_packages'));
      $query->where($conditions);
      $db->setQuery($query);
      $db->execute();

      $query->clear();
      $conditions = array(
        $db->quoteName('package_id') . ' IN (' . implode(',', $packageIds) . ')'
      );
      $query->delete($db->quoteName('#__formea_backup_forms'));
      $query->where($conditions);
      $db->setQuery($query);
      $db->execute();

      foreach ($packages as $package)
      {
        if (is_dir(Path::clean($this->generatedMediaPath . $package['key'])))
        {
          Folder::delete($this->generatedMediaPath . $package['key']);
        }
      }

      return $this->getPackageLists($args);

    }

    private function packageLists($db_limit = [], $ordering = ['id' => 'DESC'], $search = '')
    {
      $limit  = 5;
      $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'];
        }
      }

      $db    = $this->getDatabase();
      $query = $db->getQuery(true);

      $query->select('*');
      $query->from($db->quoteName('#__formea_backup_packages'));

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

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


      $query = clone $query;
      $query->clear('limit')->clear('offset')->clear('order');

      $db->setQuery($query);
      $db->execute();
      $total = $db->getNumRows();

      if (!empty($packageLists))
      {
        $totalPackageLists = count($packageLists);
        for ($i = 0; $i < $totalPackageLists; $i++)
        {
          //get all package lists
          $query->clear();
          $query->select('*');
          $query->from($db->quoteName('#__formea_backup_forms'))
            ->where($db->quoteName('package_id') . ' = ' . $db->quote($packageLists[$i]->id));
          $query->order('id DESC');
          $db->setQuery($query);
          $packgeForms = $db->loadObjectList();
          if (empty($packgeForms))
          {
            $packgeForms = [];
          }
          $totalPackageForms = count($packgeForms);
          for ($j = 0; $j < $totalPackageForms; $j++)
          {
            $packgeForms[$j]->selected = false;
          }
          $packageLists[$i]->selected = false;
          $packageLists[$i]->forms    = $packgeForms;

        }
      }
      else
      {
        $packageLists = [];
      }

      $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;
      }
      $_orderingText = '';
      foreach ($ordering as $column => $direction)
      {
        $_orderingText = $column . '-' . $direction;
      }
      $ret = [
        'pagination' => [
          'total'      => $total,
          'limit'      => $limit,
          'offset'     => $offset,
          'page'       => (int) $page,
          'fromResult' => $fromResult,
          'toResult'   => $toResult,
          'search'     => $search,
          'ordering'   => $_orderingText,
        ],
        'items'      => $packageLists,
      ];

      return $ret;
    }

    private function checkFormBackupCompletion($form, $arguments)
    {
      $complete = 1;
      if ($arguments->package_id != 0 && !empty($arguments->form))
      {

        if ($form->elements != 1)
        {
          $complete = 0;
        }
        if ($form->layouts != 1)
        {
          $complete = 0;
        }
        if ($form->submissions != -1)
        {
          if ($form->submissions == 0)
          {
            $complete = 0;
          }
        }

        if ($complete == 1)
        {
          $source   = $this->generatedMediaPath . $arguments->secret_key . '/' . $arguments->form->id . '/';
          $formInfo = [
            'title'          => $form->title,
            'form_title'     => $form->form_title,
            'created'        => (new \Feseur\Library\FsrDate())->toSql(),
            'formea_version' => FormeaGeneralHelper::getCurrentVersion(),
            'note'           => (isset($form->note)) ? $form->note : '',
          ];
          $filename = $source . 'formea_backup.json';
          File::write($filename, json_encode($formInfo));
        }

      }
      else
      {
        $complete = 0;
      }


      return $complete;
    }

    public function finaliseBackup($args = [])
    {

      $package = $args['package'];
      if (is_array($package))
      {
        $package = json_decode(json_encode($package));
      }
      $container = Factory::getContainer();
      /** @var DatabaseDriver $db */
      $db         = $container->get('DatabaseDriver');
      $packageSrc = $this->generatedMediaPath . $package->secret_key . '/';
      //compress the files
      $targetFiles = ['formea_backup.json', 'elements.json', 'layouts.json', 'grouped_map.json', 'submissions.json', 'form.json', 'groupedElements.json', 'submissions', 'attachments'];
      $formZips    = [];
      $totalForms  = count($package->forms);
      for ($i = 0; $i < $totalForms; $i++)
      {
        $source     = $packageSrc . $package->forms[$i]->id . '/';
        $zipName    = \Joomla\Filter\OutputFilter::stringUrlSafe($package->forms[$i]->title);
        $zipFile    = $source . $zipName . '.zip';
        $formZips[] = $zipFile;
        $this->zipSelectedFilesAndDirs($source, $zipFile, $targetFiles);
        //delete all files and directories
        foreach ($targetFiles as $targetFile)
        {
          if ($targetFile === 'submissions' || $targetFile === 'attachments')
          {
            if (is_dir(Path::clean($source . $targetFile)))
            {
              Folder::delete($source . $targetFile);
            }
          }
          else
          {
            if (is_file(Path::clean($source . $targetFile)))
            {
              File::delete($source . $targetFile);
            }
          }
        }
        $this->insertBlockerFiles($source);
        $formFilePath      = str_replace(JPATH_ROOT, '', $zipFile);
        $updForm           = new stdClass();
        $updForm->id       = $package->forms[$i]->id;
        $updForm->filepath = $formFilePath;
        $db->updateObject('#__formea_backup_forms', $updForm, 'id');
        $package->forms[$i]->filepath = $formFilePath;
      }

      //create package info
      $packageTitle = 'Package #' . $package->id;
      $packageInfo  = [
        'title'          => $packageTitle,
        'total_forms'    => count($formZips),
        'created'        => (new \Feseur\Library\FsrDate())->toSql(),
        'formea_version' => FormeaGeneralHelper::getCurrentVersion(),
        'note'           => (isset($package->id)) ? $package->id : '',
      ];
      $filename     = $packageSrc . 'formea_backup_package.json';
      File::write($filename, json_encode($packageInfo));

      $pkgZipName = \Joomla\Filter\OutputFilter::stringUrlSafe($packageTitle);
      $zipFile    = $packageSrc . $pkgZipName . '.zip';

      $packageFiles = ['formea_backup_package.json'];

      foreach ($formZips as $formZip)
      {
        $zipInfo   = pathinfo($formZip);
        $_filename = $zipInfo['basename'];
        $newDest   = $packageSrc . $_filename;
        File::copy($formZip, $newDest);
        $packageFiles[] = $_filename;
      }


      $this->zipSelectedFilesAndDirs($packageSrc, $zipFile, $packageFiles);

      foreach ($packageFiles as $file)
      {
        File::delete($packageSrc . $file);
      }

      $pkgFilePath          = str_replace(JPATH_ROOT, '', $zipFile);
      $updPackage           = new stdClass();
      $updPackage->id       = $package->id;
      $updPackage->filepath = $pkgFilePath;
      $db->updateObject('#__formea_backup_packages', $updPackage, 'id');
      $package->filepath = $pkgFilePath;

      return $package;
    }

    private function zipSelectedFilesAndDirs($source, $destination, $targetFiles)
    {
      if (!extension_loaded('zip') || !file_exists($source))
      {
        return false;
      }

      $zip = new ZipArchive();
      if (!$zip->open($destination, ZipArchive::CREATE | ZipArchive::OVERWRITE))
      {
        return false;
      }

      $source = realpath($source);

      foreach ($targetFiles as $fileOrDir)
      {
        $filePath = realpath($source . DIRECTORY_SEPARATOR . $fileOrDir);

        if ($filePath && file_exists($filePath))
        {
          if (is_file($filePath))
          {
            // Add individual file to the archive
            $zip->addFile($filePath, $fileOrDir); // Preserve the path inside the ZIP
          }
          elseif (is_dir($filePath))
          {
            // Add directory and its contents recursively
            $iterator = new RecursiveDirectoryIterator($filePath, FilesystemIterator::SKIP_DOTS);
            $files    = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);

            // Add the directory itself
            $zip->addEmptyDir($fileOrDir); // Preserve the directory path

            // Add all files inside the directory
            foreach ($files as $file)
            {
              $file = realpath($file);
              if (is_dir($file))
              {
                // Add empty subdirectories
                $relativePath = str_replace($source . DIRECTORY_SEPARATOR, '', $file . DIRECTORY_SEPARATOR);
                $zip->addEmptyDir($relativePath);
              }
              elseif (is_file($file))
              {
                // Add files in subdirectories
                $relativePath = str_replace($source . DIRECTORY_SEPARATOR, '', $file);
                $zip->addFile($file, $relativePath);
              }
            }
          }
        }
      }

      return $zip->close();
    }

    private function getAllImageSrcFromHtml($html)
    {
      if (empty($html))
      {
        return [];
      }
      // Load HTML content
      $dom = new DOMDocument();
      @$dom->loadHTML($html); // Suppress errors due to malformed HTML

      // Create DOMXPath object
      $xpath = new DOMXPath($dom);

      // Get all img elements
      $imgElements = $xpath->query("//img");

      // Initialize an array to store src values
      $srcArray = [];

      foreach ($imgElements as $img)
      {
        // Add each src attribute to the array
        $srcArray[] = $img->getAttribute('src');
      }

      return $srcArray;
    }

    private function insertBlockerFiles($targetDirectory)
    {
      $files = ['.htaccess', 'index.html', 'index.htm', 'index.php', 'web.config'];
      foreach ($files as $file)
      {
        $src = $this->backupPath . 'src/Assets/' . $file;
        if (is_file($src))
        {
          File::copy($src, $targetDirectory . $file);
        }
      }
    }

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

    /**
     * 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_backup_packages` (
`id` int NOT NULL AUTO_INCREMENT,
`secret_key` VARCHAR(255) NULL DEFAULT NULL,
`note` TEXT NULL DEFAULT NULL,
`filepath` VARCHAR(255) NULL 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();
          }
        }
      }

      $query   = 'CREATE TABLE IF NOT EXISTS `#__formea_backup_forms` (
`id` int NOT NULL AUTO_INCREMENT,
`package_id` int DEFAULT NULL,
`form_id` int DEFAULT NULL,
`form_title` VARCHAR(255) NULL DEFAULT NULL,
`title` VARCHAR(255) NULL DEFAULT NULL,
`note` TEXT NULL DEFAULT NULL,
`filepath` VARCHAR(255) NULL DEFAULT NULL,
`submissions` TINYINT NOT NULL DEFAULT \'0\',
`elements` TINYINT NOT NULL DEFAULT \'0\',
`layouts` TINYINT NOT NULL DEFAULT \'0\',
`complete` TINYINT NOT NULL DEFAULT \'0\',
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;
    }

    /**
     * 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_backup_packages`;';
      $query   .= 'DROP TABLE IF EXISTS `#__formea_backup_forms`;';
      $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;
    }

  }
