<?php

/**
 * @package     Joomla.Site
 * @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\Site\Libraries;

defined('_JEXEC') or die;

use Exception;
use Feseur\Library\FsrResponse;
use Joomla\CMS\Factory;
use Joomla\Filesystem\Folder;
use Joomla\CMS\Language\Text;
use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
use Joomla\Database\DatabaseDriver;
use Joomla\Filesystem\Path;
use Joomla\Registry\Registry;
use stdClass;

class FormeaCore
{
  /**
   * @var string
   * @since 1.0.0
   */
  public $formUniqueString;

  /**
   * @var int
   * @since 1.0.0
   */
  public $totalPages = 0;

  /**
   * @var int
   * @since 1.0.0
   */
  public $styleId = 0;

  /**
   * @var int
   * @since 1.0.0
   */
  public $id = 0;

  /**
   * @var int
   * @since 1.0.0
   */
  public $formId = 0;

  /**
   * @var int
   * @since 1.0.0
   */
  public $group_id = 0;

  /**
   * @var Registry
   * @since 1.0.0
   */
  public $formParams;

  protected $coreType = '';

  /**
   * @var \stdClass | null
   * @since 1.0.7
   */
  public $formObject = null;

  public function __construct($config = [])
  {
    if (isset($config['formId'])) {
      $this->formId = $config['formId'];
    } else {
      $this->formId = 0;
    }

    if (isset($config['group_id'])) {
      $this->group_id = $config['group_id'];
    } else {
      $this->group_id = 0;
    }

    if (isset($config['formObject'])) {
      $this->formObject = $config['formObject'];
    } else {
      $this->formObject = null;
    }

    if (isset($config['formUniqueString'])) {
      $this->formUniqueString = $config['formUniqueString'];
    } else {
      $this->formUniqueString = '';
    }

    if (isset($config['id'])) {
      $this->id = $config['id'];
    } else {
      $this->id = 0;
    }

    if (isset($config['styleId'])) {
      $this->styleId = $config['styleId'];
    } else {
      $this->styleId = 0;
    }

    if (isset($config['totalPages'])) {
      $this->totalPages = $config['totalPages'];
    } else {
      $this->totalPages = 0;
    }

    if (isset($config['formParams'])) {
      $this->formParams = $config['formParams'];
    } else {
      $this->formParams = new Registry([]);
    }
  }


  public function drawPageElementAttribute($formId, $currentIdx, $totalPages)
  {
    return [
      'pageAttributes'    => [],
      'pageClass'         => [],
      'pageFeedbackClass' => []
    ];
  }

  public function set($prop, $val)
  {
    $this->{$prop} = $val;
  }

  /**
   * Get the inline JS script to be pushed in the header
   *
   * @since 1.0.0
   */
  public function getGeneratedScript()
  {
    return '';
  }

  /**
   * Get the inline CSS to be pushed in the header
   *
   * @since 1.0.0
   */
  public function getGeneratedStyle()
  {
    return '';
  }

  /**
   * JS file list to load
   * @since 1.0.0
   */
  public function getLoadableScript()
  {
    return [];
  }

  /**
   * CSS file list to load
   * @since 1.0.0
   */
  public function getLoadableStyle()
  {
    return [];
  }

  /**
   * @param   FormeaElement  $element
   *
   * @since 1.0.0
   */
  public function getInputAttributes($element)
  {
    return [];
    // var_dump($element->id);die;
  }

  /**
   * @param   FormeaGridItem  $gridItem
   *
   * @return array
   * @since 1.0.0
   */
  public function getInputGroupContainerAttributes($gridItem)
  {
    return [];
  }

  public function checkElementBeforeSubmissions($elements)
  {
    return $elements;
  }

  public function refactorGroupBlock($htmlStructure, $groupedElement)
  {
    return $htmlStructure;
  }


  /**
   * Method to manipulate HTML rendered layout before displaying
   *
   * @param $html
   *
   * @return mixed
   * @since 1.0.6
   */
  public function onBeforeDisplayHtml($html)
  {
    return $html;
  }

  /**
   * Method to call right before storing data in #__formea_submissions.
   *
   * @param   stdClass  $submission  this object will not contain submission id as it's not yet stored.
   *
   * @since 1.1.0
   * @return stdClass
   */
  public function onBeforeStoreSubmission($submission)
  {
    return $submission;
  }

  /**
   * Method to call after the form has been submitted, be it with a submission error or not
   *
   * @param   FormeaSubmissionResponse  $submissionResponse
   *
   * @return FormeaSubmissionResponse
   * @since 1.1.0
   */
  public function onAfterSubmission($submissionResponse)
  {
    return $submissionResponse;
  }

  public function deleteCorePlugin()
  {
    $retObject = new FsrResponse();
    try {
      if ((int) $this->id < 1) {
        throw new Exception(Text::_('COM_FORMEA_NO_THEME_SELECTED'));
      }

      $container = Factory::getContainer();
      /** @var DatabaseDriver $db */
      $db    = $container->get('DatabaseDriver');
      $query = $db->getQuery(true);

      $coreObject = FormeaGeneralHelper::getCoreExtension($this->id);
      if (empty($coreObject)) {
        throw new Exception(Text::_('COM_FORMEA_NO_THEME_FOUND'));
      }
      // delete all custom keys for user 1001.
      $conditions = array(
        $db->quoteName('id') . ' = ' . $this->id
      );

      $query->clear();
      $query->delete($db->quoteName('#__formea_cores'));
      $query->where($conditions);
      $db->setQuery($query);
      $db->execute();

      $conditions = array(
        $db->quoteName('extension_id') . ' = ' . $this->id,
        $db->quoteName('extension_type') . ' = 0',
      );

      $query->clear();
      $query->delete($db->quoteName('#__formea_extension_styles'));
      $query->where($conditions);
      $db->setQuery($query);
      $db->execute();


      $conditions = array(
        $db->quoteName('corename') . ' = ' . $db->quote($coreObject->name)
      );

      $query->clear();
      $query->delete($db->quoteName('#__formea_form_cores'));
      $query->where($conditions);
      $db->setQuery($query);
      $db->execute();

      //formea_group_cores
      $query->clear();
      $query->delete($db->quoteName('#__formea_group_cores'));
      $query->where($conditions);
      $db->setQuery($query);
      $db->execute();
      if (is_dir(Path::clean(FORMEA_CORE_PATH . '/' . $coreObject->name))) {
        $elName    = $coreObject->name;
        $className = 'Formea' . $elName;
        require_once FORMEA_CORE_PATH . '/' . $elName . '/' . $className . '.php';
        /** @var FormeaCore $elClass */
        $elClass = new $className();
        $done    = $elClass->onDeleteCore();
        Folder::delete(FORMEA_CORE_PATH . '/' . $coreObject->name);
      }
      if (is_dir(Path::clean(JPATH_ROOT . '/media/com_formea/css/core/' . $coreObject->name))) {
        Folder::delete(JPATH_ROOT . '/media/com_formea/css/core/' . $coreObject->name);
      }
      if (is_dir(Path::clean(JPATH_ROOT . '/media/com_formea/js/core/' . $coreObject->name))) {
        Folder::delete(JPATH_ROOT . '/media/com_formea/js/core/' . $coreObject->name);
      }

      $retObject->setSuccess(true);
      $retObject->setResult((object) [
        'deleted_core' => $coreObject
      ]);
    } catch (Exception $e) {
      $retObject->setSuccess(false);
      $retObject->setMsg($e->getMessage());
    }

    return $retObject;
  }

  /**
   * Method to call when open on admin view
   *
   * @return void
   * @since 1.1.0
   */
  public function onAdminView() {}

  /**
   * Before core being deleted
   * @return boolean
   *
   * @since 1.1.0
   */
  public function onDeleteCore()
  {
    return true;
  }

  /**
   * @param   array   $submitted_data
   * @param   array   $placeholders
   * @param   array   $args
   * @param   string  $langTag
   *
   * @return array
   *
   * @since 1.2.1
   */
  public function processPlaceholder($submitted_data, $placeholders = [], $args = [], $langTag = 'en-GB')
  {
    return $placeholders;
  }
}
