<?php
/**
 * Environment badge for admin bar.
 *
 * @package WP_PowerSuite\AdminColorCustomizer
 */

namespace WP_PowerSuite\AdminColorCustomizer;

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

class Environment_Badge {

	private bool $hooks_registered = false;

	/**
	 * @param array<string, mixed> $settings
	 */
	public function register_hooks( array $settings ): void {
		$env = is_array( $settings['environment_badge'] ?? null ) ? $settings['environment_badge'] : [];
		if ( empty( $env['enabled'] ) || $this->hooks_registered ) {
			return;
		}

		$this->hooks_registered = true;
		add_action( 'admin_bar_menu', [ $this, 'add_admin_bar_badge' ], 999 );
		add_action( 'admin_head', [ $this, 'print_badge_styles' ] );
		add_action( 'wp_head', [ $this, 'print_badge_styles' ] );
	}

	public function add_admin_bar_badge( \WP_Admin_Bar $admin_bar ): void {
		if ( ! is_user_logged_in() || ! is_admin_bar_showing() ) {
			return;
		}

		$settings = Settings::get_effective_settings();
		$env      = is_array( $settings['environment_badge'] ?? null ) ? $settings['environment_badge'] : [];

		if ( empty( $env['enabled'] ) ) {
			return;
		}

		$label = $this->get_label( $env );

		$admin_bar->add_node(
			[
				'id'    => 'wpps-acc-environment-badge',
				'title' => esc_html( $label ),
				'meta'  => [
					'class' => 'wpps-acc-env-badge',
				],
				'href'  => false,
			]
		);
	}

	public function print_badge_styles(): void {
		if ( ! is_user_logged_in() || ! is_admin_bar_showing() ) {
			return;
		}

		$settings = Settings::get_effective_settings();
		$env      = is_array( $settings['environment_badge'] ?? null ) ? $settings['environment_badge'] : [];

		if ( empty( $env['enabled'] ) ) {
			return;
		}

		$color = Scheme_Registry::sanitize_hex_color( $env['color'] ?? '#cc0000' ) ?? '#cc0000';

		echo '<style>#wpadminbar #wp-admin-bar-wpps-acc-environment-badge > .ab-item{background:' . esc_attr( $color ) . ';color:#fff;font-weight:600;}</style>';
	}

	/**
	 * @param array<string, mixed> $env
	 */
	public function get_label( array $env ): string {
		$type = sanitize_key( (string) ( $env['type'] ?? 'production' ) );

		if ( $type === 'custom' ) {
			$custom = sanitize_text_field( (string) ( $env['label'] ?? '' ) );
			return $custom !== '' ? $custom : __( 'Custom', 'wp-powersuite' );
		}

		if ( $type === 'staging' ) {
			return __( 'Staging', 'wp-powersuite' );
		}

		if ( $type === 'development' ) {
			return __( 'Development', 'wp-powersuite' );
		}

		if ( $type === 'production' ) {
			$wp_env = function_exists( 'wp_get_environment_type' ) ? wp_get_environment_type() : 'production';
			return match ( $wp_env ) {
				'staging'     => __( 'Staging', 'wp-powersuite' ),
				'development', 'local' => __( 'Development', 'wp-powersuite' ),
				default       => __( 'Production', 'wp-powersuite' ),
			};
		}

		return __( 'Environment', 'wp-powersuite' );
	}
}
