<?php
/**
 * Adds WordPress Admin bar submenu for Essential Grid.
 *
 * @package   Essential_Grid
 * @author    ThemePunch <info@themepunch.com>
 * @link      https://www.essential-grid.com/
 * @copyright 2025 ThemePunch
 */

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

/**
 * Admin bar Class For Essential Grid.
 * Add edit links for on-page grids.
 */
class Essential_Grid_Adminbar {

	/**
	 * Instance of this class.
	 *
	 * @var null|object
	 */
	protected static $instance = null;

	/**
	 * Return an instance of this class.
	 *
	 * @return object A single instance of this class.
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Set up hooks.
	 */
	private function __construct() {
		add_action( 'wp_footer', array( $this, 'add_admin_bar' ), 100 );
		add_action( 'wp_before_admin_bar_render', array( $this, 'add_admin_menu_nodes' ) );
	}

	/**
	 * Check that admin bar shown on frontend.
	 *
	 * @return bool
	 */
	private function is_admin_bar_on_frontend() {
		return ! is_admin() && is_super_admin() && is_admin_bar_showing();
	}

	/**
	 * Additional js for admin bar.
	 */
	public function add_admin_bar() {
		if ( ! $this->is_admin_bar_on_frontend() ) {
			return;
		}
		include ESG_PLUGIN_PATH . 'public/views/admin-bar.php';
	}

	/**
	 * Add admin nodes.
	 *
	 * @throws Exception In case there are issues with database.
	 */
	public function add_admin_menu_nodes() {
		if ( ! $this->is_admin_bar_on_frontend() ) {
			return;
		}

		$this->add_node(
			'<span class="esg-label">Essential Grid</span>',
			false,
			admin_url( 'admin.php?page=essential-grid' ),
			array( 'class' => 'esg-menu menupop' ),
			'esg'
		);
	}

	/**
	 * Add admin node.
	 *
	 * @param string      $title Node title.
	 * @param bool|string $parent Node parent handle.
	 * @param string      $href Node URL.
	 * @param array       $custom_meta Node meta data.
	 * @param string      $handle Node handle.
	 * @return void
	 */
	protected function add_node( $title, $parent = false, $href = '', $custom_meta = array(), $handle = '' ) {
		global $wp_admin_bar;

		if ( ! $this->is_admin_bar_on_frontend() ) {
			return;
		}

		$handle = ( '' === $handle ) ? strtolower( str_replace( ' ', '-', $title ) ) : $handle;
		$meta   = ( strpos( $href, site_url() ) !== false ) ? array() : array( 'target' => '_blank' );
		$meta   = array_merge( $meta, $custom_meta );

		$wp_admin_bar->add_node(
			array(
				'parent' => $parent,
				'id'     => $handle,
				'title'  => $title,
				'href'   => $href,
				'meta'   => $meta,
			)
		);
	}
}
