<?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\Extension;

defined('JPATH_PLATFORM') or die;

use Feseur\Library\FsrHelper;
use JLoader;
use Joomla\CMS\Categories\CategoryServiceInterface;
use Joomla\CMS\Categories\CategoryServiceTrait;
use Joomla\CMS\Component\Router\RouterServiceInterface;
use Joomla\CMS\Component\Router\RouterServiceTrait;
use Joomla\CMS\Extension\BootableExtensionInterface;
use Joomla\CMS\Extension\MVCComponent;
use Joomla\CMS\Factory;
use Joomla\Filesystem\File;
use Joomla\CMS\HTML\HTMLRegistryAwareTrait;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\WebAsset\WebAssetManager;
use Joomla\Component\Formea\Administrator\Service\HTML\AdministratorService;
use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
use Joomla\Filesystem\Path;
use Psr\Container\ContainerInterface;

/**
 * Component class for com_formea
 *
 * @since  1.0.0
 */
class FormeaComponent extends MVCComponent
implements BootableExtensionInterface, CategoryServiceInterface, RouterServiceInterface
{
  use CategoryServiceTrait;
  use HTMLRegistryAwareTrait;
  use RouterServiceTrait;

  /**
   * Booting the extension. This is the function to set up the environment of the extension like
   * registering new class loaders, etc.
   *
   * If required, some initial set up can be done from services of the container, eg.
   * registering HTML services.
   *
   * @param   ContainerInterface  $container  The container
   *
   * @return  void
   *
   * @since   1.0.0
   */
  public function boot(ContainerInterface $container)
  {
    $this->getRegistry()->register('formeasadministrator', new AdministratorService);
    $this->_setConstants();
    $this->_loadLibraries();
  }

  protected function _setConstants()
  {
    $siteUrl = 'https://feseur.com';
    if (!defined('FORMEA_DEV_LINK')) {
      define('FORMEA_DEV_LINK', $siteUrl);
    }
    if (!defined('FORMEA_DOC_LINK')) {
      define('FORMEA_DOC_LINK', $siteUrl . '/resources/docs/formea');
    }
    if (!defined('FORMEA_SUPPORT_LINK')) {
      define('FORMEA_SUPPORT_LINK', $siteUrl . '/support');
    }
    if (!defined('FORMEA_RESOURCE_LINK')) {
      define('FORMEA_RESOURCE_LINK', $siteUrl . '/resources');
    }
    if (!defined('FORMEA_PLG_PATH')) {
      define('FORMEA_PLG_PATH', JPATH_ROOT . '/components/com_formea/plugins');
    }
    if (!defined('FORMEA_CORE_PATH')) {
      define('FORMEA_CORE_PATH', FORMEA_PLG_PATH . '/core');
    }
    if (!defined('FORMEA_THEME_PATH')) {
      define('FORMEA_THEME_PATH', FORMEA_PLG_PATH . '/theme');
    }
    if (!defined('FORMEA_ELEMENT_PATH')) {
      define('FORMEA_ELEMENT_PATH', FORMEA_PLG_PATH . '/element');
    }
    if (!defined('FORMEA_VALIDATION_PATH')) {
      define('FORMEA_VALIDATION_PATH', FORMEA_PLG_PATH . '/validation');
    }
    if (!defined('FORMEA_ADMIN')) {
      define('FORMEA_ADMIN', JPATH_ROOT . '/administrator/components/com_formea');
    }
  }

  protected function _loadLibraries()
  {


    $app = Factory::getApplication();
    if ($app->isClient('administrator')) {
      $additionalWebAssets = [];
      $formeaExtensions    = FormeaGeneralHelper::getFormeaExtensions();
      $namespaces          = [];
      if (!empty($formeaExtensions)) {
        $totalFormeaExtensions = count($formeaExtensions);
        for ($i = 0; $i < $totalFormeaExtensions; $i++) {
          $determineNameSpace = $this->determineNameSpace($formeaExtensions[$i], $formeaExtensions[$i]->extension_type);
          if (isset($determineNameSpace['namespace'])) {
            if (!empty($determineNameSpace['namespace'])) {
              $namespaces[] = $determineNameSpace['namespace'];
            }
          }

          if (isset($determineNameSpace['webAsset'])) {
            if (!empty($determineNameSpace['webAsset'])) {
              $additionalWebAssets[] = $determineNameSpace['webAsset'];
            }
          }
        }
      }


      /** @var WebAssetManager $wa */
      $wa = $app->getDocument()->getWebAssetManager();
      $wa->registerAndUseStyle('formea-admin', 'media/com_formea/css/admin.min.css');

      $fsrGlobal = [
        "url"      => Uri::base(),
        "ss"       => Session::getFormToken(),
        "loader"   => Uri::root() . 'media/com_formea/img/loader.svg',
        "datum"    => (object) [],
        "langText" => '{}',
        "langTag"  => $app->getLanguage()->getTag()
      ];
      $wa->addInlineScript("var FsrGlobal = " . json_encode($fsrGlobal) . ";");
      if (!empty($additionalWebAssets)) {
        $registerWa               = $wa->getRegistry();
        $totalAdditionalWebAssets = count($additionalWebAssets);
        for ($j = 0; $j < $totalAdditionalWebAssets; $j++) {
          $registerWa->addRegistryFile($additionalWebAssets[$j]);
        }
      }
    }
  }

  protected function determineNameSpace($extension, $type = 'core')
  {
    $namespaces = '';
    $webAssets  = '';
    if ($type == 'element') {
      $pluginsPath = FORMEA_ELEMENT_PATH;
    } elseif ($type == 'theme') {
      $pluginsPath = FORMEA_THEME_PATH;
    } elseif ($type == 'validation') {
      $pluginsPath = FORMEA_VALIDATION_PATH;
    } else {
      $pluginsPath = FORMEA_CORE_PATH;
    }
    $xml      = $pluginsPath . '/' . $extension->name . '/' . $extension->name . '.xml';
    $webAsset = $pluginsPath . '/' . $extension->name . '/joomla.asset.json';
    if (is_file(Path::clean($xml))) {
      $readXml = simplexml_load_file($xml);
      if (isset($readXml->namespace)) {
        $_namespace = FsrHelper::xmlToArray($readXml->namespace);
        $_namespace = $_namespace['namespace'];
        $src        = '';
        if (isset($_namespace['@path'])) {
          $src = '/' . $_namespace['@path'];
        }
        $_str       = $_namespace['$'];
        $_src       = $pluginsPath . '/' . $extension->name . $src;
        $namespaces = $_src;
        JLoader::registerNamespace($_str, $_src);
      }
    }
    if (is_file(Path::clean($webAsset))) {
      $webAssets = 'components/com_formea/plugins/' . $type . '/' . $extension->name . '/joomla.asset.json';
    }

    return [
      'namespace' => $namespaces,
      'webAsset'  => $webAssets
    ];
  }
}
