<?php
/**
 * Admin bar quick links.
 *
 * @package B3WVS\VariationSwatches\Admin
 */

namespace B3WVS\VariationSwatches\Admin;

defined( 'ABSPATH' ) || exit;

/**
 * AdminBar Class
 *
 * Adds quick links to the WP admin bar.
 */
class AdminBar {

	/**
	 * Instance of this class.
	 *
	 * @var AdminBar
	 */
	private static $instance = null;

	/**
	 * Get instance of this class.
	 *
	 * @return AdminBar
	 */
	public static function get_instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	private function __construct() {
		// Run after core adds the "Edit" node (priority 80).
		add_action( 'admin_bar_menu', array( $this, 'add_menu_items' ), 100 );
	}

	/**
	 * Add admin bar items.
	 *
	 * @param \WP_Admin_Bar $wp_admin_bar WP Admin Bar.
	 */
	public function add_menu_items( $wp_admin_bar ) {
		if ( is_admin() ) {
			return;
		}

		if ( ! is_admin_bar_showing() ) {
			return;
		}

		if ( ! ( $wp_admin_bar instanceof \WP_Admin_Bar ) ) {
			return;
		}

		$post_id = function_exists( 'get_queried_object_id' ) ? absint( get_queried_object_id() ) : 0;
		if ( ! $post_id ) {
			return;
		}

		$queried_object = function_exists( 'get_queried_object' ) ? get_queried_object() : null;
		if ( ! ( $queried_object instanceof \WP_Post ) ) {
			return;
		}

		if ( 'product' !== $queried_object->post_type ) {
			return;
		}

		// Extra guard: respect WooCommerce conditional tag when available.
		if ( function_exists( 'is_product' ) && ! is_product() ) {
			return;
		}

		// If the user can't edit the product, they won't have the core edit menu either.
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		// The settings page uses manage_options; avoid showing a dead link.
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Core edit menu node is "edit" (e.g. "Edit product").
		if ( ! $wp_admin_bar->get_node( 'edit' ) ) {
			return;
		}

		$wp_admin_bar->add_node(
			array(
				'id'     => 'b3-wvs-edit-swatches',
				'parent' => 'edit',
				'title'  => esc_html__( 'Edit swatches', 'b3-swatches' ),
				'href'   => admin_url( 'admin.php?page=b3-swatches' ),
			)
		);
	}
}
