<?php
declare( strict_types=1 );

namespace FiboFilters\Config;

use WP_Error;
use FiboFilters\WP\Notice;

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

/**
 * Requirements class
 */
class Requirements {

	/** @var WP_Error[] */
	private $errors = [];

	/**
	 * Get all requirements errors
	 *
	 * @return WP_Error[]
	 */
	public function get_errors(): array {
		return $this->errors;
	}

	/**
	 * Check all plugin requirements
	 *
	 * @return bool
	 */
	public function check_all_requirements(): bool {
		if ( $this->test_woocommerce() ) {
			$this->test_minimum_woocommerce_version();
		}
		$this->test_minimum_wordpress_version();

		return empty( $this->errors );
	}

	/**
	 * Show requirements errors as admin notices
	 */
	public function show_errors_as_notices(): bool {
		if ( ! empty( $this->errors ) ) {
			foreach ( $this->errors as $error ) {
				Notice::display_error( $error->get_error_message() );
			}
		}

		return true;
	}

	/**
	 * Test if WooCommerce is active
	 */
	private function test_woocommerce(): bool {
		if ( ! defined( 'WOOCOMMERCE_VERSION' ) ) {
			$this->errors[] = new WP_Error(
				'fibofilters_no_woocommerce',
				sprintf(
				/* translators: 1: Plugin full name 2: WooCommerce URL at wp.org */
					_x( '%1$s is enabled but not effective. It requires %2$s in order to work.', '[admin]', 'fibofilters' ),
					'<b>' . Env::$plugin_full_name . '</b>',
					'<a href="https://wordpress.org/plugins/woocommerce/"  target="_blank">WooCommerce</a>'
				)
			);

			return false;
		}

		return true;
	}

	/**
	 * Test minimum WordPress version
	 */
	private function test_minimum_wordpress_version(): void {
		global $wp_version;
		if ( version_compare( $wp_version, Env::$wp_min_version ) < 0 ) {
			$this->errors[] = new WP_Error(
				'fibofilters_no_minimum_wordpress_version',
				sprintf(
				/* translators: 1: Plugin full name 2: Minimum WordPress version */
					_x( '%1$s is enabled but not effective. Requires WordPress %2$s or newer.', '[admin]', 'fibofilters' ),
					'<b>' . Env::$plugin_full_name . '</b>',
					'<b>' . Env::$wp_min_version . '</b>'
				)
			);
		}
	}

	/**
	 * Test minimum WooCommerce version
	 */
	private function test_minimum_woocommerce_version(): void {
		if ( defined( 'WOOCOMMERCE_VERSION' ) && version_compare( WOOCOMMERCE_VERSION, Env::$wc_min_version ) < 0 ) {
			$this->errors[] = new WP_Error(
				'fibofilters_no_minimum_woocommerce_version',
				sprintf(
				/* translators: 1: Plugin full name 2: WooCommerce URL at wp.org 3: Minimum WooCommerce version */
					_x( '%1$s is enabled but not effective. Requires the %2$s plugin to work, which is active, but must be at least version %3$s.', '[admin]', 'fibofilters' ),
					'<b>' . Env::$plugin_full_name . '</b>',
					'<a href="https://wordpress.org/plugins/woocommerce/"  target="_blank">WooCommerce</a>',
					'<b>' . Env::$wc_min_version . '</b>'
				)
			);
		}
	}
}
