<?php
/**
 * @package     MefisAssetBridge
 * @subpackage  Joomla_Administrator_Component
 *
 * @copyright   Copyright (C) 2025 Goran Usljebrka. All rights reserved.
 * @license     Proprietary — No resale or incorporation into other projects without explicit written permission. see LICENSE.txt
 */

namespace Mefi\Component\MefisAssetBridge\Administrator\Helper;

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Language\Text;
use MefisAssetBridgeCore\Auth\KeyStore;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Application\CMSApplication;
use MefisAssetBridgeCore\MefisAssetBridgeCore;
use MefisAssetBridgeCore\Auth\AuthenticatedUser;
use MefisAssetBridgeCore\DTO\AuthenticatedUserDto;

\defined('JPATH_PUBLIC') || \define('JPATH_PUBLIC', JPATH_ROOT);

/**
 * Authentication Helper
 *
 * @since  1.0.0
 */
class CoreBridgeHelper
{
    /**
     * Application instance
     *
     * @var    CMSApplication
     * @since  1.0.0
     */
    protected $app;
    protected KeyStore $KeyStore;
    /**
     * Constructor
     *
     * @param   CMSApplication  $app  Application object
     * @param   DatabaseDriver  $db   Database object
     *
     * @since   1.0.0
     */
    public function __construct(CMSApplication $app = null)
    {
        $this->app = $app ?: Factory::getApplication();
    }

    /**
     * Check if core is loaded
     *
     * @return bool True if core is loaded
     *
     * @since 1.0.0
     */
    public static function isCoreLoaded(): bool
    {
        return class_exists('MefisAssetBridgeCore\\MefisAssetBridgeCore');
    }

    /**
     * Check if user is authenticated
     *
     * @return bool True if authenticated
     *
     * @since 1.0.0
     */
    public static function isAuthenticated(): bool
    {
        if (! self::isCoreLoaded()) {
            return false;
        }

        // Get user data from session
        $session  = Factory::getApplication()->getSession();
        $userData = $session->get('mefisAssetBridge.auth');

        if (empty($userData)) {
            return false;
        }

        // Create the DTO and Auth user
        try {
            $userDto           = AuthenticatedUserDto::fromArray($userData);
            $authenticatedUser = new AuthenticatedUser($userDto);

            // Let the core class determine authentication status
            return $authenticatedUser->isAuthenticated();
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Get API base URL
     *
     * @return string API base URL
     *
     * @since 1.0.0
     */
    public static function getApiBaseUrl(): string
    {
        $params    = ComponentHelper::getParams('com_mefisassetbridge');
        $serverUrl = $params->get('server_url', 'https://asset-bridge.ugoran.com/api/v1/');

        if (empty($serverUrl)) {
            throw new \RuntimeException(Text::_('COM_MEFISASSETBRIDGE_ERROR_SERVER_URL_NOT_SET'));
        }
        // Ensure URL ends with a slash
        if (substr($serverUrl, -1) !== '/') {
            $serverUrl .= '/';
        }

        return $serverUrl;
    }
    /**
     * Get component version
     *
     * @return string Component version
     *
     * @since 1.0.0
     */
    public static function getComponentVersion(): string
    {
        // Load the component manifest
        $fileName = JPATH_ADMINISTRATOR . '/components/com_mefisassetbridge/mefisassetbridge.xml';

        if (! is_file($fileName)) {
            return '0.0.0';
        }

        $manifest = simplexml_load_file($fileName);
        if (! $manifest || $manifest->getName() !== 'extension' || empty($manifest->version)) {
            return '0.0.0';
        }

        return (string) $manifest->version;
    }
    public static function getSSLCheck(): bool
    {
        $params = ComponentHelper::getParams('com_mefisassetbridge');

        return ($params->get('ssl_check', true) == true);
    }

    public static function getEnableLog(): bool
    {
        return (bool) ComponentHelper::getParams('com_mefisassetbridge')->get('enable_log', false);
    }

    public static function getDomain(): string {
        return Uri::getInstance()->getHost();
    }
    public static function getCMSVersion(): string
    {
        return JVERSION ?? 'Unknown';
    }
    public static function getCMSType(): string
    {
        return 'Joomla!';
    }
    public static function getKeyStore(): KeyStore
    {
        $altPath = JPATH_ADMINISTRATOR . DIRECTORY_SEPARATOR . 'components'.DIRECTORY_SEPARATOR.'com_mefisassetbridge'.DIRECTORY_SEPARATOR.'keys' . DIRECTORY_SEPARATOR;

        return KeyStore::getInstance(JPATH_PUBLIC, $altPath);

    }

    public static function getId(): int
    {
        $user = Factory::getApplication()->getIdentity();
        return $user->id ?? 0;
    }

}
