<?php
/*
 * Software Name: Eorisis Setup
 * Software URI: https://eorisis.com/shop/software/joomla/setup
 * Author: Eorisis
 * Author URI: https://eorisis.com
 * Copyright: Copyright (C) 2011-2025 EORISIS. All Rights Reserved.
 * License: GNU General Public License version 2; See https://eorisis.com/gpl
 * Terms of Service: https://eorisis.com/tos
 */
namespace eorisis_setup\framework\install\lib\core\model;
\defined('_JEXEC') or die;

use eorisis_setup\framework\install\lib\core\cms\application;
use eorisis_setup\framework\install\lib\core\model\database;
use eorisis_setup\framework\install\lib\core\model\params;
use eorisis_setup\framework\install\lib\core\model\clean;
use eorisis_setup\framework\install\lib\core\model\data;

class extension
{
	public function __construct() {}

	// --------------------------------------------------

	public static function installed_version() : array
	{
		static $result = null;
		if ($result === null)
		{
			$result = self::manifest_cache('version');
		}

		return $result;
	}

	// --------------------------------------------------

	private static function manifest_cache(string $name = '') : array
	{
		static $error = '';
		static $obj = null;

		if ($obj === null)
		{
			$dbo = application::dbo();
			$query = $dbo->getQuery(true);
			$query->select($dbo->quoteName('manifest_cache'));
			$query->from($dbo->quoteName('#__extensions'));
			$query->where([
				$dbo->quoteName('type').'='.$dbo->quote(data::$ext['type']),
				$dbo->quoteName('element').'='.$dbo->quote(data::$ext['element']),
				$dbo->quoteName('folder').'='.$dbo->quote(data::$ext['group'])
			]);
			$dbo->setQuery($query);
			$result = database::get_first_result($dbo);

			$json = (string)$result['record'];
			$error = $result['error'];
			$obj = $json ? (object)\json_decode($json) : false;
		}

		if (empty((array)$obj))
		{
			$obj = false;
		}

		if ($name && $obj !== false)
		{
			$value = params::xml_attr($name, $obj);
			$value = clean::version($value);
		}
		else
		{
			$value = '';
		}

		return [
			'obj' => $obj,
			'value' => $value,
			'error' => $error
		];
	}
}
