<?php
/**
 * Admin Bar — FREE
 *
 * Hides the WordPress admin bar for users with specific roles.
 * The Pro add-on hooks into 'pnlrdb_admin_bar_remove_items'
 * to remove individual admin bar nodes.
 *
 * @package Panelra
 */

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

/**
 * Class Pnlrdb_Admin_Bar
 */
class Pnlrdb_Admin_Bar {

	/**
	 * Register hooks.
	 */
	public function __construct() {
		add_action( 'init', array( $this, 'hide_by_role' ) );
		add_action( 'admin_head', array( $this, 'hide_in_admin' ) );

		// Expose a hook for Pro to remove individual admin bar nodes.
		add_action(
			'wp_before_admin_bar_render',
			function() {
				/**
				 * Fires just before the admin bar is rendered.
				 * Pro uses this to remove specific admin bar nodes.
				 *
				 * @since 1.0.0
				 */
				do_action( 'pnlrdb_admin_bar_remove_items' );
			},
			999
		);
	}

	/**
	 * Hide the admin bar for the current user if their role is in the hide list.
	 *
	 * @return void
	 */
	public function hide_by_role() {
		if ( $this->should_hide_for_current_user() ) {
			show_admin_bar( false );
		}
	}

	/**
	 * Hide the admin bar inside wp-admin for users with a selected role.
	 *
	 * WordPress does not honour show_admin_bar( false ) for the admin area,
	 * so the toolbar and its reserved top spacing must be hidden there explicitly.
	 *
	 * @return void
	 */
	public function hide_in_admin() {
		if ( ! $this->should_hide_for_current_user() ) {
			return;
		}
		?>
		<style id="pnlrdb-hide-admin-bar">
			#wpadminbar { display: none !important; }
			html.wp-toolbar { padding-top: 0 !important; }
		</style>
		<?php
	}

	/**
	 * Determine whether the admin bar should be hidden for the current user.
	 *
	 * @return bool
	 */
	private function should_hide_for_current_user() {
		$roles = (array) get_option( 'pnlrdb_hide_admin_bar_roles', array() );
		if ( empty( $roles ) ) {
			return false;
		}

		$user = wp_get_current_user();

		return ! empty( array_intersect( (array) $user->roles, $roles ) );
	}
}
