<?php
/**
 * Validations avant enregistrement d'une cible.
 *
 * @package CVS
 * @license GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

class CVS_Preflight {

	/**
	 * @param string $target
	 * @param array  $settings
	 * @param array  $posted Raw POST cvs array (backup_ack, etc.).
	 * @return array<int,string> Error messages.
	 */
	public static function validate_target_save( $target, array $settings, array $posted = array() ) {
		$errors = array();
		$target = CVS_Settings::sanitize_version( $target );
		if ( ! $target ) {
			return $errors;
		}

		$status = CVS_Releases::get_security_status( $target );
		if ( 'insecure' === $status && empty( $settings['allow_insecure_targets'] ) ) {
			$errors[] = __( 'This release is marked insecure on wordpress.org. Enable “Allow insecure targets” or pick another version.', 'core-version-switcher-by-volade' );
		}

		if ( ! empty( $settings['require_backup_ack'] ) && empty( $posted['backup_ack'] ) ) {
			$errors[] = __( 'Confirm that you have a full backup before pinning this version.', 'core-version-switcher-by-volade' );
		}

		if ( ! CVS_Releases::php_compatible_with_target( $target ) ) {
			$errors[] = sprintf(
				/* translators: 1: PHP version, 2: target WP version */
				__( 'PHP %1$s may be incompatible with WordPress %2$s.', 'core-version-switcher-by-volade' ),
				PHP_VERSION,
				$target
			);
		}

		$url = CVS_Plugin::instance()->settings->build_download_url( $target );
		if ( $url && ! CVS_Plugin::instance()->settings->zip_exists( $url ) ) {
			$errors[] = __( 'Download package not found on wordpress.org for this version or locale.', 'core-version-switcher-by-volade' );
		}

		return $errors;
	}

	/**
	 * @param string $target
	 * @return array{errors:array,warnings:array}
	 */
	public static function compat_report( $target ) {
		$scan     = CVS_Compat::scan( $target );
		$errors   = array();
		$warnings = array();

		foreach ( array_merge( $scan['plugins'], $scan['themes'] ) as $row ) {
			if ( 'error' === ( $row['severity'] ?? '' ) ) {
				$errors[] = sprintf( '%s — %s', $row['name'], $row['issue'] );
			} else {
				$warnings[] = sprintf( '%s — %s', $row['name'], $row['issue'] );
			}
		}

		return array(
			'errors'   => $errors,
			'warnings' => $warnings,
			'scan'     => $scan,
		);
	}
}
