<?php
/**
 * WordPress dashboard widget (F4) — health badge, update count (7d), PHP error
 * count (24h), last update event, link to the CR dashboard. Reuses HealthScorer's
 * breakdown; does not recompute counts.
 *
 * @package ConflictRadar\Admin
 */

declare( strict_types=1 );

namespace ConflictRadar\Admin;

use ConflictRadar\Monitor\HealthScorer;

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

class DashboardWidget {

	public function register(): void {
		add_action( 'wp_dashboard_setup', array( $this, 'add' ) );
	}

	public function add(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		wp_add_dashboard_widget(
			'conflict_radar_dashboard_widget',
			__( 'Conflict Radar', 'conflict-radar' ),
			array( $this, 'render' )
		);
	}

	public function render(): void {
		$breakdown   = ( new HealthScorer() )->calculateWithBreakdown();
		$badge_class = DashboardPage::badgeClass( (int) $breakdown['score'] );
		$last_event  = $this->lastEvent();
		$dashboard_url = admin_url( 'admin.php?page=conflict-radar' );

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

	/**
	 * The single most recent update event, or null.
	 */
	private function lastEvent(): ?object {
		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.
		$row = $wpdb->get_row(
			"SELECT plugin_name, plugin_slug, created_at
			 FROM {$wpdb->prefix}conflict_radar_events
			 WHERE event_type IN ( 'plugin_update', 'theme_update', 'core_update' )
			 ORDER BY created_at DESC
			 LIMIT 1"
		);

		return $row ?: null;
	}
}
