<?php
/**
 * Widget tableau de bord et entrée barre d'administration.
 *
 * @package CVS
 * @license GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

class CVS_Dashboard {

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

	public function __construct( CVS_Plugin $plugin ) {
		$this->plugin = $plugin;

		add_action( 'wp_dashboard_setup', array( $this, 'register_widget' ) );
		add_action( 'admin_bar_menu', array( $this, 'admin_bar_pin' ), 90 );
	}

	public function register_widget() {
		if ( ! current_user_can( 'update_core' ) ) {
			return;
		}

		wp_add_dashboard_widget(
			'cvs_status_widget',
			__( 'Core Version Switcher', 'core-version-switcher-by-volade' ),
			array( $this, 'render_widget' )
		);
	}

	public function render_widget() {
		$target  = CVS_Settings::sanitize_version( $this->plugin->settings->get( 'target_version' ) );
		$current = get_bloginfo( 'version' );
		$url     = admin_url( CVS_Admin::instance_settings_path( $this->plugin ) );

		echo '<p><strong>' . esc_html__( 'Installed', 'core-version-switcher-by-volade' ) . ':</strong> ';
		echo esc_html( $current ) . '</p>';

		if ( $target ) {
			echo '<p><strong>' . esc_html__( 'Pinned target', 'core-version-switcher-by-volade' ) . ':</strong> ';
			echo '<span class="cvs-badge cvs-badge-active">' . esc_html( $target ) . '</span></p>';

			if ( version_compare( $current, $target, '!=' ) ) {
				$updates = is_multisite() ? network_admin_url( 'update-core.php' ) : admin_url( 'update-core.php' );
				echo '<p><a class="button button-primary" href="' . esc_url( $updates ) . '">';
				esc_html_e( 'Reinstall now', 'core-version-switcher-by-volade' );
				echo '</a></p>';
			} else {
				echo '<p class="cvs-ok">' . esc_html__( 'Target matches installed core.', 'core-version-switcher-by-volade' ) . '</p>';
			}
		} else {
			echo '<p>' . esc_html__( 'No version pin — normal updates apply.', 'core-version-switcher-by-volade' ) . '</p>';
		}

		echo '<p><a href="' . esc_url( $url ) . '">' . esc_html__( 'Open settings', 'core-version-switcher-by-volade' ) . '</a></p>';
	}

	/**
	 * @param WP_Admin_Bar $bar
	 */
	public function admin_bar_pin( $bar ) {
		if ( ! is_admin_bar_showing() || ! current_user_can( 'update_core' ) ) {
			return;
		}

		$target = CVS_Settings::sanitize_version( $this->plugin->settings->get( 'target_version' ) );
		if ( ! $target ) {
			return;
		}

		$current = get_bloginfo( 'version' );
		$title   = sprintf(
			/* translators: 1: current version, 2: target version */
			__( 'WP %1$s → %2$s', 'core-version-switcher-by-volade' ),
			$current,
			$target
		);

		$bar->add_node(
			array(
				'id'    => 'cvs-pin',
				'title' => '<span class="ab-icon dashicons dashicons-update" style="top:2px"></span> ' . esc_html( $title ),
				'href'  => admin_url( CVS_Admin::instance_settings_path( $this->plugin ) ),
				'meta'  => array(
					'title' => __( 'Core Version Switcher — pinned target', 'core-version-switcher-by-volade' ),
				),
			)
		);
	}
}
