<?php
/**
 * Site Health integration: recommended-tier tests only, never critical failures.
 *
 * @package Upgrade_Pilot
 */

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

/**
 * Class UPilot_Site_Health
 */
class UPilot_Site_Health {

	/**
	 * Report assembler.
	 *
	 * @var UPilot_Report
	 */
	private $report;

	/**
	 * Constructor.
	 *
	 * @param UPilot_Report $report Report assembler.
	 */
	public function __construct( UPilot_Report $report ) {
		$this->report = $report;
		add_filter( 'site_status_tests', array( $this, 'register_tests' ) );
	}

	/**
	 * Register our tests.
	 *
	 * @param array $tests Existing tests.
	 * @return array
	 */
	public function register_tests( $tests ) {
		$tests['direct']['upilot_readiness'] = array(
			'label' => __( 'Upgrade readiness (Upgrade Pilot)', 'upgrade-pilot' ),
			'test'  => array( $this, 'test_readiness' ),
		);
		$tests['direct']['upilot_trust'] = array(
			'label' => __( 'Plugin update trust (Upgrade Pilot)', 'upgrade-pilot' ),
			'test'  => array( $this, 'test_trust' ),
		);
		return $tests;
	}

	/**
	 * Readiness test.
	 *
	 * @return array
	 */
	public function test_readiness() {
		// Assemble on demand (cheap after the first run: all sources are cached),
		// but only if a scan has ever been started — never trigger work pre-first-run.
		$scan_state = UPilot_Store::get_option( 'upilot_scan_state', array() );
		$report     = empty( $scan_state['scan_id'] ) ? UPilot_Store::get_option( 'upilot_last_report' ) : $this->report->get();

		$result = array(
			'label'       => __( 'Your site looks ready for the next WordPress and PHP upgrades', 'upgrade-pilot' ),
			'status'      => 'good',
			'badge'       => array(
				'label' => __( 'Upgrades', 'upgrade-pilot' ),
				'color' => 'blue',
			),
			'description' => '<p>' . esc_html__( 'Upgrade Pilot found no confirmed blockers in its last readiness report.', 'upgrade-pilot' ) . '</p>',
			'actions'     => sprintf(
				'<a href="%s">%s</a>',
				esc_url( UPilot_Store::admin_url( 'admin.php?page=upgrade-pilot' ) ),
				esc_html__( 'View the readiness report', 'upgrade-pilot' )
			),
			'test'        => 'upilot_readiness',
		);

		if ( ! is_array( $report ) || empty( $report['verdict'] ) ) {
			$result['label']       = __( 'No upgrade readiness report yet', 'upgrade-pilot' );
			$result['status']      = 'recommended';
			$result['description'] = '<p>' . esc_html__( 'Run your first Upgrade Pilot readiness scan to learn whether this site is ready for the next WordPress and PHP versions.', 'upgrade-pilot' ) . '</p>';
			return $result;
		}

		if ( 'red' === $report['verdict'] ) {
			$result['label']       = __( 'Upgrade blockers were found on this site', 'upgrade-pilot' );
			$result['status']      = 'recommended';
			$result['description'] = '<p>' . esc_html(
				sprintf(
					/* translators: %s: headline, e.g. "2 confirmed blockers". */
					__( 'Upgrade Pilot found: %s. These are deterministic findings (server requirements or closed plugins), not guesses.', 'upgrade-pilot' ),
					$report['headline']
				)
			) . '</p>';
		} elseif ( 'amber' === $report['verdict'] ) {
			$result['label']       = __( 'Some items need review before your next upgrade', 'upgrade-pilot' );
			$result['status']      = 'recommended';
			$result['description'] = '<p>' . esc_html(
				sprintf(
					/* translators: %s: headline. */
					__( 'Upgrade Pilot reports: %s.', 'upgrade-pilot' ),
					$report['headline']
				)
			) . '</p>';
		}

		return $result;
	}

	/**
	 * Update-trust test.
	 *
	 * @return array
	 */
	public function test_trust() {
		// Never assemble the full report from Site Health (it can trigger wp.org
		// fetches and would write a pre-first-scan report). Event counts are one
		// cheap query on our own table.
		// The table name comes from UPilot_Store: on a network the events table is
		// network-wide (base prefix), while $wpdb->prefix is the current subsite's.
		global $wpdb;
		$events_table = UPilot_Store::table( 'events' );
		$counts       = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- own table; single cheap COUNT.
			"SELECT severity, COUNT(*) AS n FROM {$events_table} WHERE acknowledged = 0 GROUP BY severity", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- own table name.
			OBJECT_K
		);
		$full = array(
			'trust' => array(
				'unacked_critical' => isset( $counts['critical'] ) ? (int) $counts['critical']->n : 0,
				'unacked_warning'  => isset( $counts['warning'] ) ? (int) $counts['warning']->n : 0,
			),
		);

		$result = array(
			'label'       => __( 'No unusual plugin ownership or closure activity', 'upgrade-pilot' ),
			'status'      => 'good',
			'badge'       => array(
				'label' => __( 'Upgrades', 'upgrade-pilot' ),
				'color' => 'blue',
			),
			'description' => '<p>' . esc_html__( 'Upgrade Pilot watches the public WordPress.org record of your plugins for ownership changes and closures. Plugins and themes that have gone unmaintained are reported in the readiness report.', 'upgrade-pilot' ) . '</p>',
			'actions'     => sprintf(
				'<a href="%s">%s</a>',
				esc_url( UPilot_Store::admin_url( 'admin.php?page=upgrade-pilot-trust' ) ),
				esc_html__( 'View update trust events', 'upgrade-pilot' )
			),
			'test'        => 'upilot_trust',
		);

		$critical = isset( $full['trust']['unacked_critical'] ) ? (int) $full['trust']['unacked_critical'] : 0;
		$warning  = isset( $full['trust']['unacked_warning'] ) ? (int) $full['trust']['unacked_warning'] : 0;

		if ( $critical > 0 ) {
			$result['label']       = __( 'A plugin on this site was closed or flagged — review it', 'upgrade-pilot' );
			$result['status']      = 'recommended';
			$result['description'] = '<p>' . esc_html(
				sprintf(
					/* translators: %d: number of critical events. */
					_n( '%d critical plugin event needs your attention.', '%d critical plugin events need your attention.', $critical, 'upgrade-pilot' ),
					$critical
				)
			) . '</p>';
		} elseif ( $warning > 0 ) {
			$result['label']       = __( 'Some of your plugins changed hands recently', 'upgrade-pilot' );
			$result['status']      = 'recommended';
			$result['description'] = '<p>' . esc_html(
				sprintf(
					/* translators: %d: number of warning events. */
					_n( '%d plugin change is worth a look before its next update runs.', '%d plugin changes are worth a look before their next updates run.', $warning, 'upgrade-pilot' ),
					$warning
				)
			) . '</p>';
		}

		return $result;
	}
}
