<?php
/**
 * Genesis Framework.
 *
 * WARNING: This file is part of the core Genesis Framework. DO NOT edit this file under any circumstances.
 * Please do all modifications in the form of a child theme.
 *
 * @package Genesis\Updates
 * @author  StudioPress
 * @license GPL-2.0-or-later
 * @link    https://my.studiopress.com/themes/genesis/
 */

/**
 * Calculate or return the first version of Genesis to run on this site.
 *
 * @since 2.1.0
 *
 * @return string First version of Genesis to run on the site.
 */
function genesis_first_version() {
	$first_version = genesis_get_option( 'first_version' );

	if ( ! $first_version ) {
		$first_version = PARENT_THEME_VERSION;
	}

	return $first_version;
}

/**
 * Helper function for comparing the "first install" version to a user specified version.
 *
 * @since 2.1.0
 *
 * @param string $version  Version number to compare first version against.
 * @param string $operator Relationship between versions.
 * @return bool `true` if the relationship is the one specified by the operator, `false` otherwise.
 */
function genesis_first_version_compare( $version, $operator ) {
	return version_compare( genesis_first_version(), $version, $operator );
}

/**
 * Retrieve and return the database version.
 *
 * Attempt to retrieve the database version setting.
 *
 * If one does not exist, fabricate one using the `theme_version` setting if it exists, or PARENT_DB_VERSION (minus 1).
 *
 * @since 3.1.0
 *
 * @param bool $cache Use cache when retrieving version(s).
 * @return string Database version.
 */
function genesis_get_db_version( $cache = false ) {
	$db_version = genesis_get_option( 'db_version', null, $cache );

	// Return if $db_version exists and is valid.
	if ( strlen( $db_version ) >= 3 ) {
		return $db_version;
	}

	// If necessary, fabricate a db_version.
	$db_version = str_replace(
		'.',
		'',
		(string) genesis_get_option( 'theme_version', null, $cache ) ?: (string) ( (int) PARENT_DB_VERSION - 1 )
	);

	// phpcs:ignore Squiz.PHP.DisallowSizeFunctionsInLoops.Found -- We need to reevaluate on every iteration.
	while ( strlen( $db_version ) < 3 ) {
		$db_version .= '0';
	}

	return $db_version;
}
