<?php
/**
 * Runtime requirements.
 *
 * @package Carticy\Conversions\Core
 */

declare(strict_types=1);

namespace Carticy\Conversions\Core;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Checks whether the plugin can boot safely.
 */
final class Requirements {

	private const MIN_PHP = '8.0';
	private const MIN_WP  = '6.0';
	private const MIN_WC  = '8.0';

	/**
	 * Check requirements and register an admin notice when any fail.
	 *
	 * @return bool True when requirements are met.
	 */
	public static function is_met(): bool {
		$errors = self::get_errors();

		if ( empty( $errors ) ) {
			return true;
		}

		add_action(
			'admin_notices',
			static function () use ( $errors ): void {
				foreach ( $errors as $error ) {
					printf(
						'<div class="notice notice-error"><p>%s</p></div>',
						esc_html( $error )
					);
				}
			}
		);

		return false;
	}

	/**
	 * Get unmet requirement messages.
	 *
	 * @return array<int, string>
	 */
	public static function get_errors(): array {
		$errors = array();

		if ( version_compare( PHP_VERSION, self::MIN_PHP, '<' ) ) {
			$errors[] = sprintf(
				/* translators: %s: Required PHP version. */
				__( 'Carticy Conversions requires PHP %s or higher.', 'carticy-conversions-for-woocommerce' ),
				self::MIN_PHP
			);
		}

		if ( function_exists( 'get_bloginfo' ) && version_compare( get_bloginfo( 'version' ), self::MIN_WP, '<' ) ) {
			$errors[] = sprintf(
				/* translators: %s: Required WordPress version. */
				__( 'Carticy Conversions requires WordPress %s or higher.', 'carticy-conversions-for-woocommerce' ),
				self::MIN_WP
			);
		}

		if ( ! class_exists( 'WooCommerce' ) ) {
			$errors[] = __( 'Carticy Conversions requires WooCommerce to be installed and active.', 'carticy-conversions-for-woocommerce' );
		}

		if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, self::MIN_WC, '<' ) ) {
			$errors[] = sprintf(
				/* translators: %s: Required WooCommerce version. */
				__( 'Carticy Conversions requires WooCommerce %s or higher.', 'carticy-conversions-for-woocommerce' ),
				self::MIN_WC
			);
		}

		return $errors;
	}
}
