<?php
/**
 * Conflict Radar dashboard page — health score badge + component breakdown +
 * recent events. Consumes the committed HealthScorer; never recomputes scoring.
 *
 * @package ConflictRadar\Admin
 */

declare( strict_types=1 );

namespace ConflictRadar\Admin;

use ConflictRadar\Monitor\HealthScorer;

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

class DashboardPage {

	public function render(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Unauthorized', 'conflict-radar' ) );
		}

		$breakdown   = ( new HealthScorer() )->calculateWithBreakdown();
		$badge_class = self::badgeClass( (int) $breakdown['score'] );
		$events      = $this->recentEvents( 5 );

		require CONFLICT_RADAR_DIR . 'templates/admin/dashboard.php';
	}

	/**
	 * Map a score to its badge colour class. Green 80-100, Yellow 50-79, Red 0-49 (F3).
	 */
	public static function badgeClass( int $score ): string {
		if ( $score >= 80 ) {
			return 'cr-badge-green';
		}
		if ( $score >= 50 ) {
			return 'cr-badge-yellow';
		}
		return 'cr-badge-red';
	}

	/**
	 * The most recent update events, newest first.
	 *
	 * @return array<int,object>
	 */
	private function recentEvents( int $limit ): array {
		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom plugin table (wp_conflict_radar_*); WP options API / object cache not applicable to dedicated event/reporting data.
		return (array) $wpdb->get_results(
			$wpdb->prepare(
				"SELECT event_type, plugin_name, plugin_slug, version_from, version_to, created_at
				 FROM {$wpdb->prefix}conflict_radar_events
				 ORDER BY created_at DESC
				 LIMIT %d",
				$limit
			)
		);
	}
}
