<?php
/*
 * Software Name: Eorisis Pixels
 * Software URI: https://eorisis.com/shop/software/joomla/pixels
 * 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 com_eorisis_pixels\framework\install_package\lib\core\model;
\defined('_JEXEC') or die;

use com_eorisis_pixels\framework\install_package\lib\core\cms\application;
use com_eorisis_pixels\framework\install_package\lib\core\model\database;
use com_eorisis_pixels\framework\install_package\lib\core\model\params;
use com_eorisis_pixels\framework\install_package\lib\core\model\clean;

class extension
{
	const PACKAGE_NAME = 'eorisis_pixels';

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

	public function __construct() {}

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

	public static function installed_version()
	{
		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('package'),
				$dbo->quoteName('element').'='.$dbo->quote('pkg_'.self::PACKAGE_NAME)
			]);
			$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 = clean::version(params::xml_attr($name, $obj));
		}
		else
		{
			$value = '';
		}

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