<?php
/**
 * Admin Bar integration.
 *
 * Adds a "Helm" node to the WordPress toolbar with quick actions — primarily a
 * one-click "Clear cache," the way WP Engine / caching plugins surface theirs.
 * Visible on both front-end and admin for users who can manage options.
 *
 * The clear action is a nonced admin-post request that reuses the shared
 * CacheManager, then redirects back to the originating page with a brief
 * confirmation flag.
 *
 * @package Platform\Helm\Admin
 */

declare( strict_types = 1 );

namespace Platform\Helm\Admin;

use Platform\Helm\Core\CacheManager;

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

final class AdminBar {

	private const CAPABILITY    = 'manage_options';
	private const CLEAR_ACTION  = 'platform_helm_adminbar_clear_cache';

	public function register_hooks(): void {
		add_action( 'admin_bar_menu', [ $this, 'add_nodes' ], 80 );
		add_action( 'admin_post_' . self::CLEAR_ACTION, [ $this, 'handle_clear' ] );
		add_action( 'admin_notices', [ $this, 'maybe_admin_notice' ] );
	}

	public function add_nodes( \WP_Admin_Bar $bar ): void {
		if ( ! current_user_can( self::CAPABILITY ) ) {
			return;
		}

		$clear_url = wp_nonce_url(
			add_query_arg(
				[
					'action'   => self::CLEAR_ACTION,
					'helm_ref' => rawurlencode( $this->current_url() ),
				],
				admin_url( 'admin-post.php' )
			),
			self::CLEAR_ACTION
		);

		// Parent node.
		$bar->add_node( [
			'id'    => 'platform-helm',
			'title' => $this->parent_title(),
			'href'  => admin_url( 'admin.php?page=platform-helm' ),
			'meta'  => [ 'title' => __( 'Platform Helm', 'platform-helm' ) ],
		] );

		// Clear cache.
		$bar->add_node( [
			'parent' => 'platform-helm',
			'id'     => 'platform-helm-clear-cache',
			'title'  => __( 'Clear cache', 'platform-helm' ),
			'href'   => $clear_url,
		] );

		// Quick links to the main screens.
		$bar->add_node( [
			'parent' => 'platform-helm',
			'id'     => 'platform-helm-dashboard',
			'title'  => __( 'Command Center', 'platform-helm' ),
			'href'   => admin_url( 'admin.php?page=platform-helm' ),
		] );
		$bar->add_node( [
			'parent' => 'platform-helm',
			'id'     => 'platform-helm-health',
			'title'  => __( 'Link Health', 'platform-helm' ),
			'href'   => admin_url( 'admin.php?page=platform-helm-link-health' ),
		] );
	}

	private function parent_title(): string {
		// Small inline icon + label. Dashicon renders in the toolbar font.
		return '<span class="ab-icon dashicons dashicons-admin-links" style="top:2px;"></span>'
			. '<span class="ab-label">' . esc_html__( 'Helm', 'platform-helm' ) . '</span>';
	}

	public function handle_clear(): void {
		if ( ! current_user_can( self::CAPABILITY ) ) {
			wp_die( esc_html__( 'Permission denied.', 'platform-helm' ) );
		}
		check_admin_referer( self::CLEAR_ACTION );

		CacheManager::clear_all();

		// Redirect back to where the user clicked from.
		$ref = isset( $_GET['helm_ref'] ) ? esc_url_raw( wp_unslash( (string) $_GET['helm_ref'] ) ) : '';
		$ref = $ref ?: admin_url();
		$ref = add_query_arg( 'helm_cache_cleared', '1', $ref );
		wp_safe_redirect( $ref );
		exit;
	}

	public function maybe_admin_notice(): void {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( empty( $_GET['helm_cache_cleared'] ) ) {
			return;
		}
		if ( ! current_user_can( self::CAPABILITY ) ) {
			return;
		}
		echo '<div class="notice notice-success is-dismissible"><p>'
			. esc_html__( 'Platform Helm caches cleared.', 'platform-helm' )
			. '</p></div>';
	}

	private function current_url(): string {
		$scheme = is_ssl() ? 'https://' : 'http://';
		$host   = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
		$uri    = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
		if ( '' === $host ) {
			return admin_url();
		}
		return $scheme . $host . $uri;
	}
}
