<?php
/**
 * Tests Santé du site.
 *
 * @package CVS
 * @license GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

class CVS_Site_Health {

	/** @var CVS_Plugin */
	private $plugin;

	public function __construct( CVS_Plugin $plugin ) {
		$this->plugin = $plugin;
		add_filter( 'site_status_tests', array( $this, 'register_tests' ) );
	}

	public function register_tests( $tests ) {
		$tests['direct']['cvs_core_pin'] = array(
			'label' => __( 'Core version pin', 'core-version-switcher-by-volade' ),
			'test'  => array( $this, 'test_core_pin' ),
		);
		return $tests;
	}

	public function test_core_pin() {
		$target  = CVS_Settings::sanitize_version( $this->plugin->settings->get( 'target_version' ) );
		$current = get_bloginfo( 'version' );

		if ( ! $target ) {
			return array(
				'label'       => __( 'No core version pin', 'core-version-switcher-by-volade' ),
				'status'      => 'good',
				'badge'       => array(
					'label' => __( 'Core Version Switcher', 'core-version-switcher-by-volade' ),
					'color' => 'blue',
				),
				'description' => __( 'Core Version Switcher is not pinning WordPress to a specific release.', 'core-version-switcher-by-volade' ),
				'actions'     => '',
				'test'        => 'cvs_core_pin',
			);
		}

		$status_label = CVS_Releases::get_security_status( $target );
		$health       = 'recommended';
		if ( 'insecure' === $status_label ) {
			$health = 'critical';
		} elseif ( version_compare( $current, $target, '!=' ) ) {
			$health = 'recommended';
		} else {
			$health = 'good';
		}

		$settings_url = admin_url( CVS_Admin::instance_settings_path( $this->plugin ) );

		return array(
			'label'       => sprintf(
				/* translators: %s: target version */
				__( 'WordPress pinned to %s', 'core-version-switcher-by-volade' ),
				$target
			),
			'status'      => $health,
			'badge'       => array(
				'label' => __( 'Core Version Switcher', 'core-version-switcher-by-volade' ),
				'color' => 'blue',
			),
			'description' => sprintf(
				/* translators: 1: installed version, 2: security status */
				__( 'Installed: %1$s. Release status on wordpress.org: %2$s.', 'core-version-switcher-by-volade' ),
				$current,
				$status_label
			),
			'actions'     => sprintf(
				'<a href="%s">%s</a>',
				esc_url( $settings_url ),
				esc_html__( 'Open Core Version settings', 'core-version-switcher-by-volade' )
			),
			'test'        => 'cvs_core_pin',
		);
	}
}
