<?php

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

namespace Joomla\Component\Formea\Administrator\Controller;

defined('_JEXEC') or die;

use Exception;
use Feseur\Library\FsrResponse;
use Joomla\CMS\Application\CMSWebApplicationInterface;
use Joomla\CMS\Factory;
use Joomla\CMS\Form\FormFactoryInterface;
use Joomla\CMS\MVC\Factory\MVCFactoryInterface;
use Joomla\Component\Formea\Administrator\Model\CoreextensionModel;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\FormController;
use Joomla\CMS\Router\Route;
use Joomla\Filesystem\Path;
use Joomla\Input\Input;

/**
 * Controller for a single formea
 *
 * @since  1.0
 */
class CoreextensionController extends FormController
{

  /**
   * @var bool
   * @since 1.2.2
   */
  private $isDebug = false;

  public function __construct($config = [], MVCFactoryInterface $factory = null, ?CMSWebApplicationInterface $app = null, ?Input $input = null, FormFactoryInterface $formFactory = null)
  {
    parent::__construct($config, $factory, $app, $input, $formFactory);
    if (isset($config['formeamode'])) {
      if ($config['formeamode'] == 'debug') {
        $this->isDebug = true;
      }
    }
  }

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

  public function save($key = null, $urlVar = null)
  {
    $saved = parent::save($key, $urlVar); // TODO: Change the autogenerated stub
  }

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

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

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

    return parent::batch($model);
  }

  /**
   * Install a payment plugin
   */
  public function install()
  {
    $this->checkToken();
    $app    = Factory::getApplication();
    $plugin = $app->getInput()->files->getRaw('plugin_package', []);

    /** @var CoreextensionModel $model */
    $model = $this->getModel('Coreextension');

    try {
      if (empty($plugin)) {
        throw new Exception(Text::_('COM_FORMEA_NOT_FILE_UPLOADED'));
      }
      $model->install($plugin);
      $this->setRedirect(Route::_('index.php?option=com_formea&view=coreextensions', false), Text::_('COM_FORMEA_CORE_PLUGIN_INSTALLED'));
    } catch (Exception $e) {
      $this->app->enqueueMessage($e->getMessage(), 'error');
      $this->setRedirect(Route::_('index.php?option=com_formea&view=coreextensions', false), Text::_('COM_FORMEA_CORE_PLUGIN_INSTALL_ERROR'));
    }
  }

  public function apiCall()
  {
    $retObject = new FsrResponse();
    try {
      if ($this->isDebug) {
        if (!defined('FORMEA_PLG_PATH')) {
          define('FORMEA_PLG_PATH', JPATH_ROOT . '/components/com_formea/plugins');
          define('FORMEA_CORE_PATH', FORMEA_PLG_PATH . '/core');
          define('FORMEA_THEME_PATH', FORMEA_PLG_PATH . '/theme');
          define('FORMEA_ELEMENT_PATH', FORMEA_PLG_PATH . '/element');
          define('FORMEA_VALIDATION_PATH', FORMEA_PLG_PATH . '/validation');
        }
      } else {
        $method = $this->input->getMethod();
        $this->checkToken($method);
      }

      $methodName    = $this->input->getString('methodName');
      $extensionName = $this->input->getString('extensionName');
      $config        = $this->input->get('config', [], 'ARRAY');
      $args          = $this->input->get('args', [], 'ARRAY');
      $format        = $this->input->getString('format');
      $clsName       = 'Formea' . $extensionName;
      $targetFile    = $clsName . '.php';
      if (!is_file(Path::clean(FORMEA_CORE_PATH . '/' . $extensionName . '/' . $targetFile))) {
        throw new Exception('Invalid Core');
      }
      require_once FORMEA_CORE_PATH . '/' . $extensionName . '/' . $targetFile;
      if (!class_exists($clsName) || !method_exists($clsName, $methodName)) {
        throw new Exception('Invalid method');
      }
      $class  = new $clsName($config);
      $result = $class->{$methodName}($args);

      $retObject->setResult($result);
      $retObject->setSuccess(true);
    } catch (Exception $e) {
      $retObject->setSuccess(false);
      $retObject->setMsg($e->getMessage());
    }
    $legacyCores = [
      'Calculations',
      'Conditionals',
      'ModalSlide',
    ];
    if (!$this->isDebug) {
      if ($format === 'json' && !in_array($extensionName, $legacyCores)) {
        $view            = $this->getView('Formea', 'json');
        $view->retObject = $retObject;
        $view->display();

        return true;
      } else {
        echo json_encode($retObject);
        $this->app->close();
      }
    } else {
      return json_encode($retObject);
    }
  }

  private function getApiCall() {}

  private function postApiCall() {}
}
