<?php
/**
 * Préréglages de version en un clic.
 *
 * @package CVS
 * @license GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

class CVS_Presets {

	/**
	 * @return array<string,array{label:string,desc:string,icon:string,version:string}>
	 */
	public static function all( CVS_Plugin $plugin ) {
		$current  = get_bloginfo( 'version' );
		$previous = CVS_Releases::get_previous_patch( $current );
		$latest   = CVS_Releases::get_latest_version();
		$rollback = CVS_Settings::sanitize_version( get_option( CVS_Settings::PREVIOUS_VERSION_KEY, '' ) );
		$secure   = CVS_Releases::get_latest_secure_in_major( $current );

		$presets = array();

		if ( $previous && version_compare( $previous, $current, '<' ) ) {
			$presets['previous_patch'] = array(
				'label'   => __( 'Previous patch', 'core-version-switcher-by-volade' ),
				'desc'    => sprintf(
					/* translators: %s: version number */
					__( 'Rollback one patch within %s.x — ideal for bisecting a bug.', 'core-version-switcher-by-volade' ),
					explode( '.', $current )[0] . '.' . ( explode( '.', $current )[1] ?? '0' )
				),
				'icon'    => '⏪',
				'version' => $previous,
			);
		}

		if ( $rollback && version_compare( $rollback, $current, '!=' ) ) {
			$presets['rollback'] = array(
				'label'   => __( 'Rollback to last known', 'core-version-switcher-by-volade' ),
				'desc'    => sprintf(
					/* translators: %s: version number */
					__( 'Return to %s — saved before your last core switch.', 'core-version-switcher-by-volade' ),
					$rollback
				),
				'icon'    => '↩️',
				'version' => $rollback,
			);
		}

		if ( $latest && version_compare( $latest, $current, '>' ) ) {
			$presets['latest'] = array(
				'label'   => __( 'Latest WordPress', 'core-version-switcher-by-volade' ),
				'desc'    => sprintf(
					/* translators: %s: version number */
					__( 'Upgrade to the current release (%s).', 'core-version-switcher-by-volade' ),
					$latest
				),
				'icon'    => '⬆️',
				'version' => $latest,
			);
		}

		if ( $secure && version_compare( $secure, $current, '!=' ) ) {
			$presets['secure_major'] = array(
				'label'   => __( 'Latest in this major', 'core-version-switcher-by-volade' ),
				'desc'    => sprintf(
					/* translators: %s: version number */
					__( 'Stay on major %1$s with the newest still-listed release (%2$s).', 'core-version-switcher-by-volade' ),
					explode( '.', $current )[0],
					$secure
				),
				'icon'    => '🛡️',
				'version' => $secure,
			);
		}

		return $presets;
	}

	/**
	 * @return string|WP_Error
	 */
	public static function resolve( $slug, CVS_Plugin $plugin ) {
		$all = self::all( $plugin );
		if ( empty( $all[ $slug ] ) ) {
			return new WP_Error( 'invalid_preset', __( 'Unknown preset.', 'core-version-switcher-by-volade' ) );
		}
		return CVS_Settings::sanitize_version( $all[ $slug ]['version'] );
	}
}
