<?php
/**
 * Compatibility Checker — admin notice for outdated environments.
 *
 * Self-registering: instantiate once and all hooks are set up automatically.
 * Does NOT deactivate the plugin (too aggressive) — shows a warning instead.
 * Does NOT modify any existing functionality — purely additive.
 *
 * @package WahraRentalsBookings
 * @since   2.0.6
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class WAHRB_Compatibility
 */
class WAHRB_Compatibility {

	/**
	 * Recommended minimum WordPress version.
	 *
	 * @var string
	 */
	private string $rec_wp = '6.6';

	/**
	 * Recommended minimum PHP version.
	 *
	 * @var string
	 */
	private string $rec_php = '8.1';

	/**
	 * Recommended minimum WooCommerce version.
	 *
	 * @var string
	 */
	private string $rec_wc = '8.0';

	/**
	 * Constructor — register hooks.
	 */
	public function __construct() {
		add_action( 'admin_init', array( $this, 'check_compatibility' ) );
	}

	/**
	 * Run compatibility checks and attach notices if needed.
	 */
	public function check_compatibility(): void {
		$warnings = array();

		// PHP version.
		if ( version_compare( PHP_VERSION, $this->rec_php, '<' ) ) {
			$warnings[] = sprintf(
				/* translators: 1: Current PHP version, 2: Recommended PHP version */
				__( 'PHP %1$s detected — PHP %2$s or higher is recommended for optimal performance.', 'wahra-rentals-bookings' ),
				PHP_VERSION,
				$this->rec_php
			);
		}

		// WordPress version.
		$wp_version = get_bloginfo( 'version' );
		if ( version_compare( $wp_version, $this->rec_wp, '<' ) ) {
			$warnings[] = sprintf(
				/* translators: 1: Current WordPress version, 2: Recommended WordPress version */
				__( 'WordPress %1$s detected — WordPress %2$s or higher is recommended.', 'wahra-rentals-bookings' ),
				$wp_version,
				$this->rec_wp
			);
		}

		// WooCommerce version.
		if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, $this->rec_wc, '<' ) ) {
			$warnings[] = sprintf(
				/* translators: 1: Current WooCommerce version, 2: Recommended WooCommerce version */
				__( 'WooCommerce %1$s detected — WooCommerce %2$s or higher is recommended.', 'wahra-rentals-bookings' ),
				WC_VERSION,
				$this->rec_wc
			);
		}

		if ( empty( $warnings ) ) {
			return;
		}

		// Store warnings for the admin_notices callback.
		add_action(
			'admin_notices',
			function () use ( $warnings ) {
				if ( ! current_user_can( 'manage_options' ) ) {
					return;
				}

				echo '<div class="notice notice-warning is-dismissible">';
				echo '<p><strong>' . esc_html__( 'Rentals & Bookings — Compatibility Notice', 'wahra-rentals-bookings' ) . '</strong></p>';
				echo '<ul style="list-style:disc;margin-left:20px;">';
				foreach ( $warnings as $w ) {
					echo '<li>' . esc_html( $w ) . '</li>';
				}
				echo '</ul>';
				echo '<p>' . esc_html__( 'The plugin will continue to work, but updating your environment is recommended.', 'wahra-rentals-bookings' ) . '</p>';
				echo '</div>';
			}
		);
	}
}
